我是python的初学者,我想知道为什么我不能让elif条件返回true并执行代码。无论我尝试什么并为Choice输入什么,我总是得到";你好世界";打印而不是"打印";我统治着世界;
name = input("What is your name?")
print("Hello " + name)
choice = input('option 1: say Hello World or Option 2: say I rule the world?')
if choice == "option 1" or "1":
counter = 0
while counter < 50:
print("hello world")
counter += 1
elif choice == "option 2" or "2":
counter = 0
while counter < 50:
print("I rule the world")
counter += 1
这应该可以工作,因为if语句是关闭的。您也应该对要比较的选项使用小写字母。
name = input("What is your name?")
print("Hello " + name)
choice = input('option 1: say Hello World or Option 2: say I rule the world?')
if (choice.lower() == "option 1") or(choice =="1") :
counter = 0
while counter < 50:
print("hello world")
counter += 1
elif (choice.lower() == "option 2") or (choice =="2"):
counter = 0
while counter < 50:
print("I rule the world")
counter += 1
代码的问题是以下行:
if choice == "option 1" or "1":
这里你不是在看CCD_;选项1">或";1〃;,但是如果它等于"0";选项1";,或者字符串值"0";1〃,它被求值为true
,因此,您总是得到第一个循环。
它应该看起来像:
if ((choice == "option 1") or (choice == "1")):
elif:的行也是如此
elif ((choice == "option 2") or (choice == "2")):
如果您运行以下代码:
if "1":
print("true")
else:
print("false")
您将看到输出是CCD_ 3。