Python初学者-获取while true循环以检查是非答案

Python初学者-获取while true循环以检查是非答案,python,while-loop,Python,While Loop,我正在尝试编写一个包含“是”或“否”答案的问题列表,希望能够告诉用户,如果他们键入其他字符串(不是“是”或“否”),请输入“是”或“否” 我使用了一个whiletrueloop,但每次我运行它都会返回到q1 while True: q1 = input("Switch on, yes or no") q1= q1.title() if q1 == "No": print("Charge your battery") break elif q1 == "Yes": q2

我正在尝试编写一个包含“是”或“否”答案的问题列表,希望能够告诉用户,如果他们键入其他字符串(不是“是”或“否”),请输入“是”或“否”

我使用了一个whiletrueloop,但每次我运行它都会返回到q1

while True:
q1 = input("Switch on, yes or no")
q1= q1.title()

if q1 == "No":
    print("Charge your battery")
    break

elif q1 == "Yes":
    q2 = input("Screen working?")
    q2 = q2.title()
    if q2 == "No":
        print("replace screen")
        break

    elif q2 == "Yes":
        q3 = input("Ring people?")
        q3 = q3.title()
        if q3 == "No":
            print("Check your connecting to your network")
            break

        elif q3 == "Yes":
            print("Not sure")
            break

print("Thanks for using")    

为了使代码正常工作,您应该解决两个问题:

  • 压痕
  • 中断
    替换为
    继续
    (看看
    中断
    继续
    通过
    之间的区别)
以下版本应适用:

while True:
    q1 = input("Switch on, yes or no")
    q1= q1.title()

    if q1 == "No":
        print("Charge your battery")
        continue

    elif q1 == "Yes":
        q2 = input("Screen working?")
        q2 = q2.title()
        if q2 == "No":
            print("replace screen")
            continue

        elif q2 == "Yes":
            q3 = input("Ring people?")
            q3 = q3.title()
            if q3 == "No":
                print("Check your connecting to your network")
                continue

            elif q3 == "Yes":
                print("Not sure")
                continue

print("Thanks for using")    
缩进非常重要。可能是