初学者Python获取while true循环来检查是否答案

2024-04-23 10:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一些问题的答案是或否,并希望能够告诉用户输入是或否,如果他们键入另一个字符串(不是yes或no)。在

我使用了While-True循环,但每次运行这个循环都会返回到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")    

Tags: notrueinputyouriftitleyesprint
1条回答
网友
1楼 · 发布于 2024-04-23 10:18:33

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

  • 缩进
  • break替换为continue(查看here关于breakcontinue和{}之间的区别)

以下版本应该可以使用:

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")    

相关问题 更多 >