Limiting input | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Limiting input

how do i do give an output if the users inputs a wrong input. For examplen the input required in the program is supposed to be an integer and i the user accidentally inputs a string i want the program to output a message like "please input and integer"

19th Jun 2018, 4:55 PM
Muhammad Bilal
Muhammad Bilal - avatar
6 Answers
+ 1
afaik in python3.x a user always inputs a string with user_input = input("prompt: ") so even if he inputs "3", it get's stored as the string "3". If you want to check if this string is only made of numbers, you can use the isnumeric() method. for example: user_input = input("Input: ") while not user_input.isnumeric(): print("Please input an number!") user_input = input("Input: ")
19th Jun 2018, 5:26 PM
deep_unlearning
deep_unlearning - avatar
+ 1
Then you have to separately convert it with the int() function, but only after, you've made sure it's a number - otherwise you'll get an error. for example: string3 = "3" number3 = int(string3)
19th Jun 2018, 5:33 PM
deep_unlearning
deep_unlearning - avatar
+ 1
try this man if not input.isdigit(): print("Please enter number")
19th Jun 2018, 5:44 PM
‎ ‏‏‎Anonymous Guy
0
well i dont want the 3 to be stored as a string
19th Jun 2018, 5:28 PM
Muhammad Bilal
Muhammad Bilal - avatar
0
I just noticed that my method won't work for negative numbers (which are also ints in Python 3.x). Here is a solution that works for negative whole numbers as well. Example: #The ok var makes sure you're in the loop until you get a number #The try/except part tries to convert the string into an int #If there is no error, your int gets stored in the variable number # and ok turns to 1, stopping the loop ok = 0 while ok == 0: user_input = input("Input: ") try: number = int(user_input) ok = 1 except ValueError: print("Please input an integer!")
19th Jun 2018, 5:46 PM
deep_unlearning
deep_unlearning - avatar
0
Thanks alot
18th Feb 2019, 5:53 PM
Muhammad Bilal
Muhammad Bilal - avatar