Jump to content
  • Advertisement
Sign in to follow this  
Lain Rivers

Python type checking

This topic is 2521 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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:

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!