Function to Obtain Integer Value - Python Programming Exercise

In this exercise, you will 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. This exercise is perfect for practicing function definition, input validation, and loops in Python. By implementing this 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

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

 Copy 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

 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.

  •  Function to Manage Task Database

    In this exercise, you will develop a Python program to enhance the "tasks database" by dividing it into multiple functions for better organization and readability. Th...

  •  Function to Find Maximum Value in an Array

    In this exercise, you will develop a Python program containing a function that accepts a list of floating-point numbers as input and returns the maximum value within ...

  •  Iterative Implementation of the Factorial Function

    In this exercise, you will develop a Python program that calculates the factorial of a given number using an iterative (non-recursive) method. This exercise is...

  •  Function to Print Title

    In this exercise, you will develop a Python program with a function called 'WriteTitle' that displays a text in uppercase, centered on the screen with extra spaces an...

  •  Main Function Output Value

    In this exercise, you will develop a Python program that prompts the user to provide a title via the command line (using the previously defined WriteTitle function). ...

  •  Function to Calculate DV

    In this exercise, you will develop a Python program that defines a function to count the number of numeric digits and vowels in a given string. The function should ta...