Exercise
Function To Obtain Integer Value
Objective
Develop a Python program with a function named "get_int" that displays the text received as a parameter, prompts the user for an integer, and repeats the prompt if the number is not within the specified minimum and maximum values. The function should finally return the entered number. For example, if you call age = get_int("Enter your age", 0, 150), it would become:
Enter your age: 180 Not a valid answer. Must be no more than 150. Enter your age: -2 Not a valid answer. Must be no less than 0. Enter your age: 20
(The value for the variable "age" would be 20)
Example Python Exercise
Show Python Code
# Define the get_int function
def get_int(prompt, min_val, max_val):
while True:
try:
# Ask the user for a number
user_input = int(input(f"{prompt}: "))
# Validate if the number is within the range
if user_input < min_val:
print(f"Not a valid answer. Must be no less than {min_val}.")
elif user_input > max_val:
print(f"Not a valid answer. Must be no more than {max_val}.")
else:
return user_input
except ValueError:
# In case the user enters something that is not an integer
print("Invalid input. Please enter an integer.")
# Example of using the function
age = get_int("Enter your age", 0, 150)
print(f"Your age is {age}.")
Output
Enter your age: 180
Not a valid answer. Must be no more than 150.
Enter your age: -2
Not a valid answer. Must be no less than 0.
Enter your age: 20
Your age is 20.
Share this Python Exercise