或&和if语句在一行中无法按预期工作

时间:2018-06-24 02:17:13

标签: python-3.x

我不确定为什么该代码无法按预期工作,请问有人可以帮忙吗?

# 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")

我在所有可能的条件下测试了此代码,并且可以正常工作,但在最后一个条件下无法按预期工作,在最后一个条件下,不知道为什么条件为False。

我将所有经过测试的条件粘贴到这里,并且得到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
>>> 

2 个答案:

答案 0 :(得分:1)

在您编写的代码中,将user_name [0]与表达式(“ 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")

答案 1 :(得分:0)

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

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

欢呼