【问题标题】:or & and in if statement in one line not working as supposed或 & 和 if 语句在一行中没有按预期工作
【发布时间】:2018-06-24 02:17:12
【问题描述】:

我不确定为什么这段代码没有按预期工作,有人可以帮我吗?

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

【问题讨论】:

标签: python-3.x


【解决方案1】:

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

print( 'a' or 'A' )

结果是

a

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

这是一个代码 sn-p,它可以满足您的预期:

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

【讨论】:

    【解决方案2】:

    上一个测试用例没有得到预期值的原因是这种情况

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

    您看到(“a”或“A”)的评估方式与您想象的不同。括号使它成为它自己的表达式。 该表达式基本上是说 If 'a' is null then return 'A'

    因此,这总是返回 'a',返回那个输出。

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

    应该解决这个问题

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

    干杯

    【讨论】:

    • 避免索引两次:user_name[0] in ('a', 'A')
    • @布拉德·所罗门。非常感谢先生,现在我明白我犯了什么错误,以及实现这一目标的替代方法。先生还有一个问题。如果我将条件从“('a'或'A')”更改为“'a'或'A'”怎么办?
    • @BradSolomon 避免元组构造:user_name[0] in 'aA'.
    猜你喜欢
    • 2011-11-29
    • 1970-01-01
    • 2022-11-26
    • 2020-07-26
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2020-03-15
    相关资源
    最近更新 更多