Python if语句混淆[重复]

axkjgtzd  于 2023-02-11  发布在  Python
关注(0)|答案(2)|浏览(125)
    • 此问题在此处已有答案**:

(31个答案)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?(8个答案)
十小时前关门了。
我是Neewbie,我正在做CS50p,发现自己对第一个习题集感到困惑。
在www.example.com中,实现一个程序,提示用户回答生命、宇宙和万物的大问题,如果用户输入42或(不区分大小写)42或42,则输出"是",否则输出"否"。deep.py, implement a program that prompts the user for the answer to the Great Question of Life, the Universe and Everything, outputting Yes if the user inputs 42 or (case-insensitively) forty-two or forty two. Otherwise output No.
所以我做了这个:

answ = input("What is Answer to the Great Question of Life, the Universe and Everything? ")

if answ == "42" or "forty two" or "forty-two":
    print("Yes")
else:
    print("No")

但输出总是"是"。
但是如果我这样切:

answ = input("What is Answer to the Great Question of Life, the Universe and Everything? ")

if answ == "42":
    print("Yes")
elif answ == "forty-two":
    print("Yes")
elif answ == "forty two":
    print("Yes")
else:
    print("No")

它起作用了。
非常感谢你简单的回答。

vd8tlhqk

vd8tlhqk1#

您已经很接近了,但是每次都必须在or子句中添加对answ的调用

answ = input("What is Answer to the Great Question of Life, the Universe and Everything? ")

if answ == "42" or answ == "forty two" or answ == "forty-two":
    print("Yes")
else:
    print("No")
toe95027

toe950272#

第一个实现的问题是if语句中的条件,条件answ == "42" or "forty two" or "forty-two"总是True,因为表达式"forty two" or "forty-two"总是True,因为字符串"forty two"在python中被认为是一个真值。

相关问题