循环重新启动后,循环未中断



当一个输入被放入有效的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?

您正在else子句中调用main()。如果您输入一次无效响应,然后输入一个有效响应,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")

最新更新