简体   繁体   中英

How to keep variable defined inside while loop when it ends

I'm using Python 3.5. I'm using a while loop, and changing a variable inside of it (that was already defined by the user) that the user inputs:

variable = eval(input("[...]"))
while [input isn't what the user is expected to enter]:
    variable = eval(input("[Asking to enter a correct input]"))

So the loop ends when the user has entered a correct value. However, as "variable" is defined inside the while loop, when the user assigns a correct value to "variable" the loop ends and the first (and incorrect) value of "variable" is considered for the rest of the program.

How can I make it so the value that is remembered is that defined inside the while loop?

Actually, this is already the case with your code. If the while loop starts, the value of variable that is set inside the loop is kept.

Seems that you are redefining a global variable inside the while loop. To refer to the outer 'variable', you need to declare it as global. Take a look at:

Using global variables in a function other than the one that created them

The way you are declaring it, the inner 'variable' is created as a different variable from the outer 'variable' (even if they have the same name), and it gets discarded when the while loop ends, so you end up referring to the original (global) 'variable'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM