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"
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: ")
+ 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)
+ 1
try this man
if not input.isdigit():
print("Please enter number")
0
well i dont want the 3 to be stored as a string
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!")
0
Thanks alot