platov platov - 9 months ago 78
Python Question

How do I limit user input to specific integers, and keep track of exceptions, in Python 2.7?

EDIT: The suggested duplicate is incredibly helpful in regards to basic input validation. While it does cover a lot, my specific problem (failing to assign

int(evaluation)
to a variable) is only explicitly addressed here. I'm marking this separately in case anyone else has made a similarly silly mistake :)

I've spent the last few weeks playing with Python 2.7 and having a lot of fun. To learn more about
while
loops, I've created a small script which asks the user for an integer between 1 and 10.

My goal is to then be able to respond to cases in which the user responds with unexpected input, like a non-integer, or an integer outside the specified range. I've been able to fix a lot of my issues with help from other StackOverflow threads, but now I'm stumped.

First, I created a variable,
idiocy
, to keep track of exceptions. (The script is supposed to be sassy, but until I get it working, I'm the one it's making fun of.)

idiocy = 0

while 1:
evaluation = raw_input("> ")
try:
int(evaluation)
if evaluation < 1 or evaluation > 10:
raise AssertionError
except ValueError:
idiocy += 1
print "\nEnter an INTEGER, dirtbag.\n"
except AssertionError:
idiocy += 1
print "\nI said between 1 and 10, moron.\n"
else:
if idiocy == 0:
print "\nDid we finally figure out how to follow instructions?"
print "Okay, processing..."
else:
print "\nOkay, processing..."


As you can see, I'm trying to handle two different errors -- a
ValueError
for the input type, and an
AssertionError
for the integer range -- and keep track of how many times they're raised. (Really, I only care about knowing whether or not they've been raised at least once; that's all I need to insult the user.)

Anyways, when I run the script in its current form, the error response works just fine ('dirtbag' for non-integers, 'moron' for out-of-range). The problem is that even when I input a valid integer, I still get an out-of-range
AssertionError
.

I suspect that my issue has to do with my
while
logic, but I'm not sure what to do. I've added a
break
here or there but that doesn't seem to help. Any suggestions or blatant errors? Again, total Python beginner here, so I'm half winging it.

//If anyone has simpler, cleaner, or prettier ways to do this, feel free to let me know too. I'm here to learn!

Answer Source

You have int(evalutation), but you're not assigning it to anything.

Try

try:
    evaluation = int(evaluation)
    assert 0 < evaluation < 10
except ValueError:
    ...
except AssertionError:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download