首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >或者&并且在一行的if语句中不能正常工作

或者&并且在一行的if语句中不能正常工作
EN

Stack Overflow用户
提问于 2018-06-24 10:17:13
回答 2查看 48关注 0票数 0

我不确定为什么这段代码不能正常工作,有人能帮我吗?

代码语言:javascript
运行
复制
# check if a user eligible for watching coco movie or not.
# if user name starts with "a" or "A" and his age is greater then 10 then he can, else not.

user_name = input("please enter your name in letters here: ")
user_age = int(input("please enter your age in whole numbers here: "))

if user_name[0] == ("a" or "A") and user_age > 10 :
  print("you can watch coco movie")
else:
  print("sorry, you cannot watch coco")

我用所有可能的条件测试了这段代码,它工作得很好,但在最后一个条件下却不能正常工作,在最后一个条件下我不知道为什么条件是假的。

我在这里粘贴了所有测试条件和来自IDLE的结果:

代码语言:javascript
运行
复制
please enter your name in letters here: a
please enter your age in whole numbers here: 9
sorry, you cannot watch coco
>>> 
====================== RESTART: D:\MyPythonScripts\1.py ======================
please enter your name in letters here: a
please enter your age in whole numbers here: 10
sorry, you cannot watch coco
>>> 
====================== RESTART: D:\MyPythonScripts\1.py ======================
please enter your name in letters here: a
please enter your age in whole numbers here: 11
you can watch coco movie
>>> 
====================== RESTART: D:\MyPythonScripts\1.py ======================
please enter your name in letters here: A
please enter your age in whole numbers here: 9
sorry, you cannot watch coco
>>> 
====================== RESTART: D:\MyPythonScripts\1.py ======================
please enter your name in letters here: A
please enter your age in whole numbers here: 10
sorry, you cannot watch coco
>>> 
====================== RESTART: D:\MyPythonScripts\1.py ======================
please enter your name in letters here: A
please enter your age in whole numbers here: 11
sorry, you cannot watch coco
>>> 
EN

回答 2

Stack Overflow用户

发布于 2018-06-24 10:45:59

在您编写的代码中,将user_name与表达式('a‘或'A')进行比较。表达式('a‘或'A')的计算结果为'a’。尝尝这个,

print( 'a' or 'A' )

结果是

a

因此,只有当user_name以'a‘开头并且年龄大于10时,该条件才会测试为真。

下面是一段代码片段,它完成了您可能想要做的事情:

代码语言:javascript
运行
复制
if user_name[0] in 'aA' and user_age > 10 :
  print("you can watch coco movie")
else:
  print("sorry, you cannot watch coco")
票数 1
EN

Stack Overflow用户

发布于 2018-06-24 10:45:58

您的最后一个测试用例没有获得期望值的原因是这种情况

代码语言:javascript
运行
复制
user_name[0] == ("a" or "A")

您看到("a“或"A")的计算结果与您想象的不同。括号使其成为它自己的表达式。该表达式基本上是说,如果'a‘为,则返回'A'

因此,这总是返回'a‘,返回该输出。

代码语言:javascript
运行
复制
user_name[0] == "a" or user_name[0] == "A"

应该解决这个问题

查看这篇文章以获得更多的解释https://stackoverflow.com/a/13710667/9310329

干杯

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51006459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档