using Python:
Write a function named safe input(prompt,type) that works like
the Python input function, except that it only accepts the
specified type of input. The function takes two arguments:
r prompt: str
r type: int, float, str
The function will keep prompting for input until correct input of
the specified type is entered.
The function returns the input. If the input was specified to be a
number ( float or int), the value returned will be of the correct
type; that is, the function will perform the conversion.
The default for a prompt is the empty string. The default for the
type is string.
Ans:
'''
The required python function for implementing the above given requirements of the program is as follows:
'''
# Program:
# Required function
def safe_input(prompt, type_=str):
if(type_ not in (str, int, float)):
raise ValueError("Expected str, int or float.")
while True:
test = input(prompt)
try:
ret = type_(test)
except ValueError:
print("Invalid type, enter again.")
else:
break
return ret
test = safe_input("Enter a string: ")
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("Enter an integer: ",int)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("Enter a float: ",float)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("Enter a string: ")
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("Enter an integer: ",int)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("Enter a float: ",float)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("Enter a string: ")
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("Enter an integer: ", int)
print ('"{}" is a {}'.format(test,type(test)))
test = safe_input("Enter a float: ", float)
print ('"{}" is a {}'.format(test,type(test)))
# OUTPUT OF A SAMPLE RUN:
# PLEASE DO LIKE AND UPVOTE IF THIS WAS HELPFUL!
# THANK YOU SO MUCH IN ADVANCE!
Get Answers For Free
Most questions answered within 1 hours.