Python 3
Conversion and exception handling
Create a function that asks the user to enter a number and returns the number.
* function name: get_int
* parameters: prompt (string)
* returns: int
* operation:
Use the "prompt" parameter as the parameter to an input() call in
order to ask the
user for a number. Convert the number to a int using the int()
function and return
this number from the function.
but
- If the user enters something that cannot be converted using the
int() function,
print "invalid input" and keep asking until a valid int is entered.
Note that a
while True loop and exception handling is a really simple way of
doing this.
LOOP FOREVER
PROMPT FOR INPUT
TRY CONVERSION
RETURN CONVERTED INT
CATCH EXCEPTION
PRINT ERROR
Since the return statement will exit the function (and thus the
loop), the while
loop will only ever actually "loop" if an error is thrown during
conversion.
* expected output:
>>> get_int("Enter a num")
Enter a num: 4
# RETURNS 4
>>> get_int("Enter your age")
Enter your age: 29
# RETURNS 29
>>> get_int("What is your weight")
What is your weight: None of your business
invalid input
What is your weight: Bite me
invalid input
What is your weight: 0
# RETURNS 0
If you have any doubts, please give me comment...
def get_int(prompt):
while True:
inp = input(prompt+": ")
try:
return int(inp)
except ValueError:
print("invalid input")
print(get_int("Enter a num"))
print(get_int("Enter your age"))
print(get_int("What is your weight"))
Get Answers For Free
Most questions answered within 1 hours.