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]
Python type checking
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement