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