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?

9th Oct 2018, 6:44 AM
Jose
2 Answers
+ 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)}")
9th Oct 2018, 8:36 AM
Ipang
+ 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))
9th Oct 2018, 8:19 AM
strawdog
strawdog - avatar