Reputation: 47
def validnumber():
notValid=True
while(notValid==True):
number=input('Enter number between 0 and 9->')
if number=='':
print('Empty input!')
else:
try:
number=int(number)
except ValueError:
print('Number not an int value!Try Again!')
else:
if number>=0 and number<=9:
notvalid=False
return number
def main():
myvalidnumber=validnumber()
print(myvalidnumber)
main()
Hey guys. I wrote this program and just had 1 question.
-> the program does not end even if i enter a number between 0 and 9. Could anyone explain why is this happening?.
Thanks in advance :)
Upvotes: 1
Views: 114
Reputation: 77902
You already got the solution from thefourtheye. Just for the record: the canonical way to implement such a function in Python is to use an infinite loop and either a break
statement or an early return
(as in the example below). Also proper use of the continue
statement can simplify the flow:
def validnumber():
while True:
number=input('Enter number between 0 and 9->')
if number=='':
print('Empty input!')
continue
try:
number=int(number)
except ValueError:
print('Number not an int value! Try Again!')
continue
if number < 0 or number > 9:
print('Number not between 0 and 9! Try Again!')
continue
return number
Upvotes: 0
Reputation: 239473
Python's variables are case sensitive. notvalid
is not the same as notValid
. So, when you say
notvalid=False
you are creating a new variable. Just change it to
notValid = False
and you are fine.
Upvotes: 2