为什么我永远不能得到第二个条件为真?

2024-05-02 00:35:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者,我想知道为什么我不能让elif条件返回true并执行代码。无论我如何尝试和输入选择,我总是得到“hello world”打印,而不是“我统治世界”

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
 

Tags: orthenamehelloworldinputcounterrule
2条回答

这应该可以工作,因为您的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":

这里您并不是在看choice是“option 1”还是“1”,而是如果它等于“option 1”,或者字符串值“1”,它的计算结果是true,因此,您总是得到第一个循环

它应该是这样的:

if ((choice == "option 1") or (choice == "1")):

elif的行也是如此:

elif ((choice == "option 2") or (choice == "2")):

如果运行以下代码:

if "1":
    print("true")
else:
    print("false")

您将看到输出为true

相关问题 更多 >