I've created a program requiring a validation component to make sure score numbers entered are between 1 and 10, and this function will be used later on to append a list. So far I've written this:
def validation(goodNum,score):
goodNum = False
while goodNum == False:
score = raw_input("Please enter a valid score between 1 and 10 ")
try:
score = int(score)
except:
score = raw_input("Please enter a valid score between 1 and 10 ")
if score > 1 and score < 11:
goodNum == True
else:
print "Invalid input"
return score
When I run the program it continuously loops, constantly asking me to input the score as if the false variable isn't turning to true, when it should stop after validating the score. How should I go about correcting this problem?
1 Answer 1
You are not actually changing the value of goodNum:
goodNum == True
just compares goodNum to True. What you meant was:
goodNum = True
However there are other issues: When you enter a wrong score the first time that cannot be converted to an int, you come into your except block and ask for input again. At that point the result of raw_input is not turned into an int, so the following if will not work. I would suggest you change your logic to:
def validation(goodNum,score):
goodNum = False
while goodNum == False:
score = raw_input("Please enter a valid score between 1 and 10 ")
try:
score = int(score)
except:
print "Invalid input could not convert to integer"
continue # Just start over
if score > 1 and score < 11:
goodNum = True
else:
print "Invalid input, score must be between 1 and 10"
return score
Note: I don't know what your setup or experience level is, but I would recommend for you to use an IDE that automatically recognizes statements like this (statements with no effect) and let you easily debug your script by placing break points
goodNumis always False