Python新手求助:为何elif条件始终无法触发执行?
问题分析与解决
嘿,我来帮你搞定这个问题!你遇到的问题根源在于条件判断的逻辑写法错误,导致你的elif分支永远不会被触发。
错误原因拆解
你写的条件:
if choice == "option 1" or "1":
Python会把它解析成:
if (choice == "option 1") or ("1"):
这里的"1"是一个非空字符串,在Python里非空字符串属于真值,所以不管choice是什么,这个if条件都会永远成立,自然就轮不到后面的elif执行啦!
同样,你的elif条件choice == "option 2" or "2"也是一样的错误逻辑,但因为前面的if已经永远为真,所以这个分支根本没机会运行。
修正后的代码
把条件改成正确的逻辑判断,需要分别判断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?') # 修正条件:分别判断choice等于"option 1"或者等于"1" if choice == "option 1" or choice == "1": counter = 0 while counter < 50: print("hello world") counter += 1 # 同样修正elif的条件 elif choice == "option 2" or choice == "2": counter = 0 while counter < 50: print("I rule the world") counter += 1
或者更简洁的写法,可以用in来判断:
if choice in ["option 1", "1"]: # ... 代码 ... elif choice in ["option 2", "2"]: # ... 代码 ...
这样写不仅更清晰,也不容易出错~
内容的提问来源于stack exchange,提问作者camilo chapman
相关产品推荐
相关产品推荐

