0

当输入被放入无效的 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?
4

1 回答 1

1

你在你的条款main()里面打电话。else如果您输入一次无效响应,然后输入有效响应,break则将在第二次调用该函数时跳出循环,但第一次调用中的循环仍将运行。

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

def main():
    while True:
        type_of_user = input("Are you a student? ")
        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")
于 2019-11-11T19:49:15.547 回答