Skip to content

Instantly share code, notes, and snippets.

@geeksunny
Created August 14, 2012 06:09
Show Gist options
  • Save geeksunny/3346809 to your computer and use it in GitHub Desktop.
Save geeksunny/3346809 to your computer and use it in GitHub Desktop.
A simple console data input function with rudimentary type validation for Python.
def data_input(type, prompt):
# Initialize variables.
valid = False
return_value = False
# Loop until data input is valid.
while valid == False:
input = raw_input(prompt)
try:
if type == 'int':
return_value = int(input)
elif type == 'float':
return_value = float(input)
else:
return_value = input
valid = True
except ValueError:
print "Sorry, the input needs to be "+type+"! Try again."
return return_value
### Example
#>>> int_val = data_input('int', 'Please enter an integer: ')
#Please enter an integer: abc
#Sorry, the input needs to be int! Try again.
#Please enter an integer: 1.100
#Sorry, the input needs to be int! Try again.
#Please enter an integer: 1
#>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment