循环重启后循环未中断

当输入无效的while循环中时,它将重新启动该函数。但是,在函数重新启动后,输入任何输入后,循环都不会中断。

这是程序:

def main():
    type_of_user = input("Are you a student? ")
    while True:
        if type_of_user.lower() == "y":
            print("Your price is $3.50/m")
            break
        elif type_of_user.lower() == "n":
            print("Your price is $5.00/m")
            break
        else:
            print("Not valid")
            main()

如果您第一次输入y,它会起作用,并且循环会中断。

  Are you a student? y
  Your price is $3.50/m

如果您第一次输入n,它会起作用,并且循环会中断:

  Are you a student? n 
  Your price is $5.00/m

如果您是第一次输入无效的输入,即使输入是y或n,循环也不会中断:

Are you a student? b
Not valid
#now loop continues
Are you a student? y
Your price is $3.50/m
Not valid   #also prints not valid after valid inputs
Are you a student? n 
Your price is $5.00/m
Not valid
Are you a student?
oejdhoigfiugfiug 回答:循环重启后循环未中断

您正在dup2()子句中调用main()。如果您一次输入无效的响应,然后输入有效的响应,则else会在第二次调用该函数时跳出循环,但第一次调用中的循环仍将运行。

相反,您应该在循环内提​​出问题,以避免递归调用:

break
本文链接:https://www.f2er.com/3121783.html

大家都在问