Centered Text Function - Python Programming Exercise

In this exercise, you will 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. This exercise is perfect for practicing function definition, input validation, and loops in Python. By implementing this function and calling it from the main function, you will gain hands-on experience in handling function definitions, input validation, and loops in Python. This exercise not only reinforces your understanding of functions but also helps you develop efficient coding practices for managing user interactions.

 Category

Mastering Functions

 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

 Copy 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

 More Python Programming Exercises of Mastering Functions

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Underline Text Function

    In this exercise, you will develop a Python function that can center the text on the screen (assuming a screen width of 80 characters) and then underline it with hyph...

  •  Array Summation Function

    In this exercise, you will develop a Python program to calculate the sum of the elements in an array. The main function should look like this: def main(): example = [...

  •  Double Value Function

    In this exercise, you will develop a Python function named "double" to calculate and return an integer that is twice its input. This exercise is perfect for pr...

  •  Function Double with Mutable Parameter

    In this exercise, you will develop a Python function named "double_value" to calculate the double of an integer number and modify the data passed as an argument. Sinc...

  •  Function Swap with Mutable Parameters

    In this exercise, you will develop a Python program with a function called "swap" to exchange the values of two integer variables, which are passed by reference. This...

  •  Optimizing Local Variables in Functions

    In this exercise, you will develop a Python program with a function named "power" to compute the result of raising one integer to the power of another positive intege...