63.4k views
5 votes
Write a function (getIntegerData). The function will ask the user to enter integer between 1 and 100. If integer is entered between the ranges, the values will be returned.

Make sure to use try/except to control user's entry on non-numeric entries. Also, display message if integer is out of range. (python)

User Joshka
by
7.9k points

1 Answer

3 votes

Here's an example implementation of the getIntegerData function in Python that uses try/except to handle non-numeric entries and checks if the integer is within the specified range:

---------------------------------------------------------------------------------------
def getIntegerData():

while True:

try:

# Ask the user to enter an integer

integer = int(input("Please enter an integer between 1 and 100: "))

# Check if the integer is within the specified range

if integer < 1 or integer > 100:

print("Error: Integer is out of range. Please enter an integer between 1 and 100.")

continue

# If the integer is within the range, return it

return integer

except ValueError:

# Handle non-numeric entries

print("Error: Please enter a valid integer.")

---------------------------------------------------------------------------------------


To use this function, you can simply call it like this:

---------------------------------------------------------------------------------------
myInteger = getIntegerData()

print("You entered:", myInteger)

---------------------------------------------------------------------------------------

This will prompt the user to enter an integer between 1 and 100, and will keep asking until a valid integer within the specified range is entered. Once a valid integer is entered, it will be returned and printed to the console. If an invalid input is entered, an error message will be displayed and the function will continue to ask for a valid input.

User Matt Stow
by
8.5k points