So I needed a code to catch if a person enters a string instead of a number and keep asking the person to enter a valid number.
So I found this fix to my code online and though it works, I still can't understand why it works
I understand most of it, the value being set to False but;
why does while not false even loops in the first place?
And what actually keeps the loop running?
Code Snippet below:
def repeat():
correct_value = False
while not correct_value:
try:
guess = int(input())
except ValueError:
print("Please Enter a Number")
else:
correct_value = True
return guess
4 Answers 4
Have a look on a code below:
def repeat():
correct_value = False
# while not False so the correct_value = True
# so it is an equivalent of -> while True:
# while True will always run
while not correct_value:
try:
guess = int(input())
except ValueError:
print("Please Enter a Number")
else:
correct_value = True
return guess
Why does "while not false" even loops in the first place?
It loops because of the double negation which is always True.
And what's the actual really keeps the loop running?
Exactly the same while not False, which results in while True
Comments
not False means True, that's why it works in the first place. Exceptional handling is used for purposes like this. It tries to take an integer input, if the user does not enter an integer, it throws an error which is handled by the except block.
if the user does give an integer, correct_value becomes true, so not True means false so the loop terminates and the function returns the input.
Comments
not False means True. The keyword 'not' negates True to False and vise versa. A 'while False' loop will be skipped unlike 'while True' loops. Checkout this code to see what I mean:
exit = False
while exit:
print('In while loop')
break
while not exit:
print('In 2nd while loop')
break;
print('End')
Output:
In 2nd while loop
End
Comments
To add onto other answers, you can also think of it this way: In English, "not correct" means "incorrect". So "while not correct" means "while incorrect" - i.e. while the input is still incorrect.
In the same way that the opposite of "correct" is "incorrect", the opposite of False is True.
You could just as easily write your code as:
def repeat():
incorrect_value = True # assume incorrect so that loop will run at all
while incorrect_value:
try:
guess = int(input())
except ValueError:
print("Please Enter a Number")
else:
incorrect_value = False # stop the loop next time the condition is checked
return guess
not Falseevaluates toTrue. Check the docs fornot. It states: The operatornotyields True if its argument is false, False otherwise.