1
votes

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?

2
It will already work the way you want it to. If the variable is defined outside of the while loop, it'll retain the value of the last iteration of the while loop.Morgan Thrapp
That already happens, while and for loops don't create a new scope in Python.jonrsharpe
You a are aware that passing user inputs to eval() is a huge security issue, are you ?bruno desthuilliers
You're right, thank you for the replies. And no I was not, but I'm only using it for learning purposes and I'm the only one that uses the program.Asier R.

2 Answers

0
votes

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.

-1
votes

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'.