[英]How to fix a loop that runs once if value is correct 1st time. But runs for ever if the 1st value is wrong and 2nd value is correct.
I'm doing this controlled assessment. 我正在做此对照评估。 I am just a beginner so I don't know too much about python. 我只是一个初学者,所以我对python不太了解。
I have this code: 我有以下代码:
# defining qualification
def qualification():
print("\nQualification Level") # informs user what is AP + FQ
print('\n"AP" = Apprentice', '\n"FQ" = Fully-Qulaified')
user_qual = input("Enter your Qualification Level")
# error message if any other data is entered
while user_qual not in ("AP", "FQ"):
print("You have entered one or more data wrong!")
print("Please re-enter Qualification Level!")
qualification()
Every time this code runs, it runs good until the while loop. 每次运行此代码,它都会运行良好,直到while循环为止。 If I enter the correct value (ie AP or FQ) the fist time I run the code, then the while loop doesn't run, as it should. 如果我在第一次运行代码时输入正确的值(即AP或FQ),则while循环不会运行,应该运行。 But if I enter the wrong value the first time (any value that is not FQ or AP) the while loop runs as it should but then after it runs the first time, eve if I enter the correct value after entering the wrong value the while loop doesn't stop looping. 但是,如果我是第一次输入错误的值(不是FQ或AP的任何值),则while循环会按预期运行,但是在第一次运行后,如果在输入while的值后输入正确的值,则前夕循环不会停止循环。 A infinite loop is being created. 正在创建无限循环。
Please provide an answer, remember I'm just a beginner at programming with python, so please don't let the solution be too complicated. 请提供答案,请记住我只是python编程的初学者,所以请不要让解决方案过于复杂。
You tried to use recursion at the wrong place. 您试图在错误的地方使用递归。
If the user input is wrong for the first time, you will get into a deeper level recursion that will (maybe) input the right input (or will go deeper). 如果用户输入第一次是错误的,您将进入更深层次的递归,它将(可能)输入正确的输入(或更深层次)。
But then, it will end and go back to the previous level of recursion, where the user_qual
variable is still the same, which will result in infinite loop. 但随后,它将结束并返回上一级递归,其中user_qual
变量仍然相同,这将导致无限循环。
Note: variables are not the same while running into a different recursion level. 注意:在运行不同的递归级别时,变量并不相同。 You are getting into another local scope. 您正在进入另一个本地范围。 You might want to do a little search about scopes before you continue with your program. 在继续执行程序之前,您可能需要对范围进行一些搜索。
So, instead of calling to qualification()
on the last line, just input again: 因此,无需在最后一行调用qualification()
,只需再次输入:
while user_qual not in ("AP", "FQ"):
print("You have entered one or more data wrong!")
user_qual = input("Please re-enter Qualification Level!")
Another solution will be to use global user_qual
in the beginning of the function and in the beginning of the loop. 另一个解决方案是在函数的开头和循环的开头使用global user_qual
。 Read about global variables in python if you plan to act so. 如果您打算这样做,请阅读python中的全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.