Exercise
Centered Text Function
Objective
Develop a Python function named "get_int" that displays the text received as a parameter, prompts the user for an integer number, repeats if the number is not between the minimum and maximum values indicated as parameters, and finally returns the entered number:
age = get_int("Enter your age", 0, 150)
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 function get_int which takes a prompt message, minimum, and maximum values as parameters
def get_int(prompt, min_val, max_val):
while True: # Start an infinite loop to keep asking until a valid input is received
try:
# Display the prompt message and get the input from the user, then try to convert it to an integer
user_input = int(input(f"{prompt}: ")) # Prompt the user for input and convert it to an integer
# Check if the input is within the specified range
if user_input < min_val:
print(f"Not a valid answer. Must be no less than {min_val}.") # If input is too small, show error
elif user_input > max_val:
print(f"Not a valid answer. Must be no more than {max_val}.") # If input is too large, show error
else:
return user_input # If the input is valid, return the value and exit the loop
except ValueError:
# Handle the case where input is not an integer
print("Not a valid number. Please enter a valid integer.") # Display error for invalid input
# Main code to call get_int and store the result in the variable 'age'
age = get_int("Enter your age", 0, 150) # Call the get_int function with a prompt message and range of 0-150
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
Share this Python Exercise