0
Python: Error checking inputs
How can you make sure that I puts from a person are the correct type (string, float, instance)? For example: If I want to get an input that is an integer and a string is entered, then an error will be sent back. random_number=int(input(“Enter an integer “)) Is there a way to use a loop to make sure a string or float is not entered as an input?
2 ответов
+ 2
Made two functions to force input as int or float based on strawdog's answer
def getInt(prompt):
while True:
try:
n = int(input(prompt))
return n
except ValueError:
print("\nTry again ...")
def getFloat(prompt):
while True:
try:
n = float(input(prompt))
return n
except ValueError:
print("\nTry again ...")
i = getInt("Enter an integer: ")
print(f"Okay you entered {i} which is {type(i)}")
f = getFloat("Enter a float: ")
print(f"Okay you entered {f} which is {type(f)}")
+ 1
Looks like this will do the thing:
while True:
try:
val = int(input("Enter an integer: "))
break
except:
print("Wrong input!")
pass
print("Your integer is "+str(val))