Created
August 14, 2012 06:09
-
-
Save geeksunny/3346809 to your computer and use it in GitHub Desktop.
A simple console data input function with rudimentary type validation for Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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