Skip to content

Instantly share code, notes, and snippets.

@davegotz
Created February 19, 2019 15:36
Show Gist options
  • Save davegotz/3b177d324d938a88e026fcfb2aa4e33d to your computer and use it in GitHub Desktop.
Save davegotz/3b177d324d938a88e026fcfb2aa4e33d to your computer and use it in GitHub Desktop.
# Validated input function for numbers min-max.
# This function will ensure that numbers are:
# 1. Not too big
# 2. Not too small
# 3. Valid integers
def input_integer_in_range(prompt, min_val, max_val):
user_num = None
while user_num == None:
try:
user_num = int(input(prompt))
if user_num < min_val:
print("You entered a number that is too small. Try again.")
user_num = None
elif user_num > max_val:
print("You entered a number that is too big. Try again.")
user_num = None
except ValueError:
print("Please enter a valid integer.")
return user_num
# Test the validated input function multiple times.
def main():
for i in range(15):
prompt = "Enter number " + str(i) + " (-10-30): "
print("You entered: ", input_integer_in_range(prompt, -10, 30))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment