繁体   English   中英

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

[英]or & and in if statement in one line not working as supposed

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

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

在您编写的代码中,将user_name [0]与表达式(“ a”或“ A”)进行比较。 表达式(“ a”或“ A”)的计算结果为“ a”。 尝试这个,

print( 'a' or 'A' )

结果是

a

因此,仅当user_name以'a'开头且年龄大于10时,条件才测试为true。

这是一个代码片段,它可以实现您的预​​期目的:

if user_name[0] in 'aA' and user_age > 10 :
  print("you can watch coco movie")
else:
  print("sorry, you cannot watch coco")

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

user_name[0] == ("a" or "A")

您会看到(“ a”或“ A”)的评估结果与您想像的有所不同。 括号使它成为自己的表达。 该表达式基本上说如果'a'为null,则返回'A'

因此,它始终返回“ a”,并返回该输出。

user_name[0] == "a" or user_name[0] == "A"

应该解决这个问题

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

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM