You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:25:16