Checking if input is an integer [duplicate] - python

This question already has answers here:
How to check for an integer in Python 3.2?
(4 answers)
Closed 8 years ago.
I am not sure how to use isinstance, but here is what I tried:
age = int(input("Enter your Age: "))
if isinstance(age,int):
continue
else:
print ("Not an integer")
What am I doing wrong here? Also will this make my program terminate? Or ask me to re-enter my age?
I want it to keep asking me to re-enter if input is not an integer.

That's not going to work if the user enters something other than an integer, because the call to int() will trigger a ValueError. And if int() does succeed, there's no need to check isinstance() any longer. Also, continue only makes sense within a for or while loop. Instead, do this:
while True: # keep looping until we break out of the loop
try:
age = int(input("Enter your age: "))
break # exit the loop if the previous line succeeded
except ValueError:
print("Please enter an integer!")
# If program execution makes it here, we know that "age" contains an integer

isinstance(object, class-or-type-or-tuple) -> bool
age = int(input("Enter your Age: "))
In [6]: isinstance(age, int)
Out[6]: True
Try recursive function. with try except
def solve():
try:
age = int(input('enter age: '))
solve()
except ValueError:
print('invalid value')
solve()

Just for fun :) another possible answer without handling exceptions (probably inefficient):
age=raw_input('Enter your age: ')
while len ([ii for ii in age if not ii in [str(jj) for jj in range(9)]]) > 0:
print 'It\'s not an integer\n'
age=raw_input('Enter your age: ')
age=int(age)

Related

'Perfect factorial' python program [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.

Python | Expecting type INT, but if STR entered?

I'm asking the user for an integer type input. But if the user accidentally inputs string type, I want it to tell the use they incorrectly answer the question. Like this:
question1 = int(input("Enter a number: "))
if question1 != int:
print("Please enter a number.")
else:
...
Please note I am a beginner, and therefore do not understand expect style coding.
Thank you for your time.
Casting a string to an integer will only work if the string looks like an integer.
Anything else will raise a ValueError.
My suggestion is to catch this ValueError and inform the user appropriately.
try:
question1 = int(input("Enter a number: "))
except ValueError:
print("That's not a number!")
else:
print("Congratulations - you followed the instructions")
You can use str.isdigit() method to check if the input contains digits only
question1 = input("Enter a number: ")
if question1.isdigit():
question1= int(question1)
else:
print("Not a number")

Printing numbers as long as an empty input is not entered

If I'm asking for a user input of numbers which continues as long as an empty string is not entered, if an empty string is entered then the program ends.
My current code is:
n=0
while n != "":
n = int(input("Enter a number: "))
But obviously this isn't exactly what I want. I could remove the int input and leave it as a regular input, but this will allow all types of inputs and i just want numbers.
Do i ago about this a different way?
calling int() on an empty string will cause a ValueError so you can encapsulate everything in a try block:
>>> while True:
try:
n = int(input('NUMBER: '))
except ValueError:
print('Not an integer.')
break
NUMBER: 5
NUMBER: 12
NUMBER: 64
NUMBER:
not a number.
this also has the added benefit of catching anything ELSE that isn't an int.
I would suggest using a try/except here instead.
Also, with using a try/except, you can instead change your loop to using a while True. Then you can use break once an invalid input is found.
Also, your solution is not outputting anything either, so you might want to set up a print statement after you get the input.
Here is an example of how you can put all that together and test that an integer is entered only:
while True:
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
If you want to go a step further, and handle numbers with decimals as well, you can try to cast to float instead:
while True:
try:
n = float(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break

Making a variable integer input only == an integer in Python

Im trying to make my variable integer input to be only == to an integer, and if its not I want to print and error message. I have put this in a if statement. I always get an error when I input a string instead of my error message.
age = int(input("Enter age:"))
if age != int:
print("Not a number")
you have to use raw_input instead of input
if you want this to repeat until you have the correct value you can do this
while True:
try:
age = int(raw_input("Enter age:"))
except ValueError:
print("Not a number")
if age == desired_age: # note I changed the name of your variable to desired_age instead of int
break
I dont recommend you use variable names like int... its generally a bad practice
from the discussion i posted the link above:
age = input("Enter age:") # raw_input("Enter age:") in python 2
try:
age = int(age)
except ValueError:
print('not a number!')
the idea is to try to cast age to an integer.
your attempt of age != int will always fail; age is a string (or an int if you were successful in casting it) and int is a class.

Easier way to find if string is a number in Python 3 [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm quite new to programming. I was trying to figure out how to check if a user input (which get stores as a string) is an integer and does not contain letters. I checked some stuff on the forum and in the end came up with this:
while 1:
#Set variables
age=input("Enter age: ")
correctvalue=1
#Check if user input COULD be changed to an integer. If not, changed variable to 0
try:
variable = int(age)
except ValueError:
correctvalue=0
print("thats no age!")
#If value left at 1, prints age and breaks out of loop.
#If changed, gives instructions to user and repeats loop.
if correctvalue == 1:
age=int(age)
print ("Your age is: " + str(age))
break
else:
print ("Please enter only numbers and without decimal point")
Now, this works as shown and does what I want (ask the persons age untill they enter an integer), however is rather long for such a simple thing. I've tried to find one but I get too much data that I don't understand yet.
Is there a simple shorter way or even a simple function for this to be done?
You can make this a little shorter by removing the unnecessary correctvalue variable and breaking or continue-ing as necessary.
while True:
age=input("Enter age: ")
try:
age = int(age)
except ValueError:
print("thats no age!")
print ("Please enter only numbers and without decimal point")
else:
break
print ("Your age is: " + str(age))
Use isdigit()
"34".isdigit()
>>> "34".isdigit()
True
>>> "3.4".isdigit()
False
>>>
So something like this:
while True:
#Set variables
age=input("Enter age: ")
#Check
if not age.isdigit():
print("thats no age!")
continue
print("Your age is: %s" % age)
age = int(age)
break
This works for nonnegative integers (i.e., without a sign marker):
variable = ''
while True:
variable = input("Age: ")
if variable.isdigit():
break
else:
print("That's not an age!")
variable = int(variable)
The idea is that you loop continuously until the user inputs a string that contains only digits (that's what isdigit does).
Your code can be made a bit shorter like this. I was going to suggest changing your correctvalue variable from an integer 1 or 0 to a boolean True or False but it is redundant anyway. continue can be used to repeat the loop as necessary.
while True:
age = input("Enter age: ")
try:
age = int(age)
except ValueError:
print("That's no age!")
print("Please enter only numbers and without decimal point")
continue
print ("Your age is: " + str(age))
break

Categories