我不确定为什么这段代码不能正常工作,有人能帮我吗?
# 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的结果:
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
>>> 发布于 2018-06-24 10:45:59
在您编写的代码中,将user_name与表达式('a‘或'A')进行比较。表达式('a‘或'A')的计算结果为'a’。尝尝这个,
print( 'a' or 'A' )
结果是
a
因此,只有当user_name以'a‘开头并且年龄大于10时,该条件才会测试为真。
下面是一段代码片段,它完成了您可能想要做的事情:
if user_name[0] in 'aA' and user_age > 10 :
print("you can watch coco movie")
else:
print("sorry, you cannot watch coco")发布于 2018-06-24 10:45:58
您的最后一个测试用例没有获得期望值的原因是这种情况
user_name[0] == ("a" or "A")您看到("a“或"A")的计算结果与您想象的不同。括号使其成为它自己的表达式。该表达式基本上是说,如果'a‘为,则返回'A'
因此,这总是返回'a‘,返回该输出。
user_name[0] == "a" or user_name[0] == "A"应该解决这个问题
查看这篇文章以获得更多的解释https://stackoverflow.com/a/13710667/9310329
干杯
https://stackoverflow.com/questions/51006459
复制相似问题