第二个函数中的else语句无法正常工作问题排查求助
排查答题程序中question2函数else语句失效的问题
兄弟,先看你贴的代码片段,question2函数的写法有明显的语法错误——你写的那个问题字符串 "2.) Which of the following is a 100 player roya" 没闭合引号,而且函数体直接半截没写完,这会直接导致程序抛出语法异常,连question2函数都没法正常定义,更别说执行到else分支了。咱们先从修复这个基础问题入手,再一步步排查其他可能的原因:
1. 先补全语法错误
先把question2函数补成完整的结构,参考你第一个question函数的写法就行,比如:
def question2(): print("2.) Which of the following is a 100 player royale game?") print("A.) Fortnite") print("B.) Apex Legends") print("C.) Valorant") print("D.) Overwatch") answer = input() if answer == "A" or answer == "a": print("Correct") winsound.PlaySound("SystemExit", winsound.SND_ALIAS) else : print("Incorrect") winsound.PlaySound("SystemHand", winsound.SND_ALIAS) # 重点!别忘了调用这个函数!你之前只调用了question() question2()
2. 如果补全后else还是不执行,检查这几个点
- 是不是没调用question2函数?:你原来的代码最后只写了
question(),没调用question2(),函数都没执行,自然走不到else分支。 - 输入判断逻辑有没有漏洞?:比如用户输入的时候不小心带了空格(比如打了
A而不是A),这时候你的判断会不匹配,但这种情况应该会走到else;要是你误把条件写成了and而不是or(比如answer == "A" and answer == "a"),那永远触发不了正确分支,不过这时候else会一直执行,和你的问题刚好相反。 - 有没有不小心修改了answer的值?:比如获取输入后加了其他处理,把answer改了,导致判断逻辑出错。
3. 调试小技巧
可以在函数里加一行打印,看看实际获取的输入是什么,方便定位问题:
def question2(): print("2.) Which of the following is a 100 player royale game?") print("A.) Fortnite") print("B.) Apex Legends") print("C.) Valorant") print("D.) Overwatch") answer = input() # 打印输入的原始内容,看看是不是和你预期的不一样 print(f"你实际输入的内容是: '{answer}'") if answer == "A" or answer == "a": print("Correct") winsound.PlaySound("SystemExit", winsound.SND_ALIAS) else : print("Incorrect") winsound.PlaySound("SystemHand", winsound.SND_ALIAS) question2()
这样就能直观看到输入的内容,快速找到问题所在。
内容的提问来源于stack exchange,提问作者Student Alec Roberts
相关产品推荐
相关产品推荐

