Python中else语句失效,非法输入错误触发分支求助
问题修复:输入任意内容均触发第一个分支的bug
问题根源
你的代码存在两个关键逻辑错误:
or运算符使用错误:if cmd == "yes" or "y"这种写法不符合Python语法逻辑。因为"y"是一个非空字符串,在布尔判断中会被视为True,所以这个条件永远成立,不管用户输入什么,都会直接进入第一个分支。同理,starting_room函数里的方向判断也犯了同样的错误。- 未处理非法输入的分支:外层
if cmd in yes_no:只处理了合法输入的情况,但当用户输入不在yes_no列表中的内容时,没有对应的分支来打印错误提示。
修复步骤
修正
or的条件写法:- 将
if cmd == "yes" or "y"改为if cmd in ["yes", "y"](或完整的if cmd == "yes" or cmd == "y") - 同理,把
elif cmd == "no" or "n"改为elif cmd in ["no", "n"] starting_room函数里的方向判断也做同样修改,比如if cmd in ["north", "n"]
- 将
补充非法输入的处理分支:
- 在
start函数的外层if语句后添加else分支,用来打印else_msg,处理用户输入不在yes_no中的情况。
- 在
修复后的完整代码
import time yes_no = ['yes', 'y', 'no', 'n'] directions = ['north', 'n', 'south', 's', 'east', 'e', 'west', 'w'] else_msg = "Invalid command" def start(): print("-------------------------------") print("Welcome to Haunted Funhouse") print("Do you want to proceed? (y/n)") cmd = input(">") if cmd in yes_no: if cmd in ["yes", "y"]: time.sleep(1) print("\n------------------") print("Get ready") print("--------------------\n") starting_room() elif cmd in ["no", "n"]: time.sleep(1) print("Okay, shutting down") quit() else: print(else_msg) def starting_room(): print("-----------Start-----------") print("You stand in a octagon room") print( "There are windows to the northwest, northeast, southeast, southwest") print("There are doors to the:\n- North\n- South\n- East\n- West") print("---------------------------------------------------------") print("Where do you want to go? (n/s/e/w)") cmd = input(">") if cmd in directions: if cmd in ["north", "n"]: time.sleep(1) print("You enter through the north door") elif cmd in ["south", "s"]: time.sleep(1) print("You go through the south door") elif cmd in ["west", "w"]: time.sleep(1) print("You enter through the west door") elif cmd in ["east", "e"]: time.sleep(1) print("You enter through the east door") else: print(else_msg) start()
内容的提问来源于stack exchange,提问作者The0Wolf1
相关产品推荐
相关产品推荐

