Sign in to follow this  
Lain Rivers

Python type checking

Recommended Posts

I'm having troubles with type checking user inputs. I don't want the program to close out if they enter something other than an integer and I've been dilly-dallying with this for awhile now. Any and all type checking advice would be greatly appreciated.

[source lang="python"]

number = int(raw_input('Enter a number between 1 and 10: '))

while not 1 <= number <= 10:
print 'Invalid Entry'
int(raw_input('Please enter a number from 1 to 10: '))

if not isinstance(number):
print 'Invalid Entry'
int(raw_input('Please enter a number from 1 to 10: '))

print number
[/source]

Share this post


Link to post
Share on other sites
int() will raise a ValueError exception if the string you hand it can't be parsed as an integer, so you want to recognize that kind of exception when you feed it bad data. Off the top of my head, something like:
[code]
def get_number():
while True:
string_data = raw_input('Enter a number between 1 and 10:')
try:
number = int(string_data)
if number >= 1 and number <= 10:
return number
print "%d is not between 1 and 10" % number
except ValueError:
print "'%s' is not a valid integer." % string_data
[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this