Python代码if语句失效:输入‘no’无法终止问答程序的问题
Python问答程序无法终止的问题解决
问题原因
你这段代码的问题出在缩进错误:你仅将print("Let's play! ")和score = 0纳入了if playing.lower() == "yes"的代码块,而后续所有的问答、得分计算逻辑都在if块之外。Python靠缩进区分代码块,不在if块内的代码会无条件执行,所以不管你输入yes还是no,问答环节都会强制运行。
修改方案
把所有问答流程、结果输出的代码都缩进,放到if的代码块内部;同时可以添加else分支,处理用户输入no的场景:
print("Welcome to my quiz page!") playing = input("Do you want to play? ") if playing.lower() == "yes": print("Let's play! ") score = 0 answer = input("What is the capital of Japan? ") if answer.lower() == "tokyo": print("Correct!") score += 1 else: print("Incorrect!") answer = input("What is a female Japanese dress called? ") if answer.lower() == "kimono": print("Correct!") score += 1 else: print("Incorrect!") answer = input("What are Japanese gang members called? ") if answer.lower() == "yakuza": print("Correct!") score += 1 else: print("Incorrect!") print("You've got " + str(score) + " questions correct!") print("You've got " + str((score / 3) * 100) + "%") else: print("Okay, maybe next time!")
这样修改后,只有用户输入yes时才会启动问答流程;输入no(或其他非yes内容)时,程序会输出提示后直接终止。
内容的提问来源于stack exchange,提问作者Wii
相关产品推荐
相关产品推荐

