Your code would become:
def Survey():
print('1) Blue')
print('2) Red')
print('3) Yellow')
while True:
try:
question = int(input('Out of these options\(1,2,3), which is your favourite?'))
break
except:
print("That's not a valid option!")
if question == 1:
print('Nice!')
elif question == 2:
print('Cool')
elif question == 3:
print('Awesome!')
else:
print('That\'s not an option!')
The way this works is it makes a loop that will loop infinitely until only numbers are put in. So say I put '1', it would break the loop. But if I put 'Fooey!' the error that WOULD have been raised gets caught by the except statement, and it loops as it hasn't been broken.
Your code would become:
def Survey():
print('1) Blue')
print('2) Red')
print('3) Yellow')
while True:
try:
question = int(input('Out of these options\(1,2,3), which is your favourite?'))
break
except:
print("That's not a valid option!")
if question == 1:
print('Nice!')
elif question == 2:
print('Cool')
elif question == 3:
print('Awesome!')
else:
print('That\'s not an option!')
The way this works is it makes a loop that will loop infinitely until only numbers are put in. So say I put '1', it would break the loop. But if I put 'Fooey!' the error that WOULD have been raised gets caught by the except statement, and it loops as it hasn't been broken.
The best way would be to use a helper function which can accept a variable type along with the message to take input.
def _input(message, input_type=str):
while True:
try:
return input_type (input(message))
except:pass
if __name__ == '__main__':
_input("Only accepting integer : ", int)
_input("Only accepting float : ", float)
_input("Accepting anything as string : ")
So when you want an integer , you can pass it that i only want integer, just in case you can accept floating number you pass the float as a parameter. It will make your code really slim so if you have to take input 10 times , you don't want to write try catch blocks ten times.
Question| how to make the user enter only integers
How to make users only enter integer values in Python program - Stack Overflow
How to accept only integer or float inputs?
I don't understand why you don't just use floats?
while True:
try:
time = float(raw_input("How much time has elapsed since your last stop (in hours)?"))
except ValueError:
print("Enter a valid number of hours!")
continueBy typing an integer value, it'll just turn it into a float anyway.
More on reddit.comHow take a input only as integer in python?
Hello,
I have a task to take a number from the user and determine whether it is divisible by 3, 2 or both.
If the number puts something that is not integer, the program will ask them to try again.
can someone help please?
thanks.
Let the user enter anything he wishes, and warn only if it wasn't an integer:
try:
num = int(input("enter number: "))
except ValueError:
print("you must enter an integer")
This is the Pythonic way to do it, after all it's "Easier to ask forgiveness than permission".
Yes this could be a while loop such as
while 1:
instr = input('Enter an integer')
try:
val = int(instr)
print 'integer entered', val
break
except ValueError:
print instr, ' is not an integer'
My current code accepts integers that are greater than 0, which is what I want, but I also want to accept floats/decimals as well. How would I do this? Here is my current code:
while True:
try:
time = int(input("How much time has elapsed since your last stop (in hours)?"))
except ValueError:
print("Enter a valid number of hours!")
continue
if time > 0:
givenTime[2] = time
breakIndentation is off here for some reason, but believe me when I say that the indentation in the actual code is correct..
Can I just do time = int or float(input("How much time has elapsed since your last stop (in hours)?")) or would this be wrong? Any help would be appreciated.
edit: nope,
time = int or float(input("How much time has elapsed since your last stop (in hours)?"))
doesn't work.
I don't understand why you don't just use floats?
while True:
try:
time = float(raw_input("How much time has elapsed since your last stop (in hours)?"))
except ValueError:
print("Enter a valid number of hours!")
continue
By typing an integer value, it'll just turn it into a float anyway.
here's something I wrote a few months ago for a similar question. Figure out how to modify it to do what you want:
def input_type(msg, type_converter):
while True:
s = input(msg)
try :
return type_converter(s)
except ValueError as e:
print(e)
def input_lessthan(msg, maximum, type_converter=int):
while True:
n = input_type(msg, type_converter)
if n <= maximum:
return n
print("Please enter a number less than {}".format(maximum))
print(input_lessthan("hours worked> ", 168, float))
remove eval and your code is correct:
mark = raw_input("What is your mark?")
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print("This is not a number")
Just checking for a float will work fine:
try:
float(mark)
except ValueError:
print("This is not a number")
Is it easier to declare a global value than to pass an argument, In my case it's also gives an error.
def getInput():
global value
value = input()
while not value.isnumeric():
print("enter a number")
value = input("enter again")
return int(value)
getInput()
print(value)
#can't comment :)