1

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?

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
Asier R.
  • 443
  • 1
  • 5
  • 11
  • 5
    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 Oct 14 '15 at 14:00
  • 2
    That already happens, `while` and `for` loops don't create a new scope in Python. – jonrsharpe Oct 14 '15 at 14:01
  • You a are aware that passing user inputs to `eval()` is a _huge_ security issue, are you ? – bruno desthuilliers Oct 14 '15 at 14:04
  • 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. Oct 14 '15 at 14:53

2 Answers2

1

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.

Ingrid
  • 516
  • 6
  • 18
-1

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

Community
  • 1
  • 1