Making a variable integer input only == an integer in Python - 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.

Related

Python - unable to assign numerical value to empty input for math calculation

I am trying to create a program where the user has to input 3 numbers to be displayed by the range function. However, I am trying to assign a numerical value to when an empty input is given to one of the variables. Here is part of my code. For this section of the code, I want to assign a value of zero when the user enters empty input. However, when I try running this section of the program, I get this error: line 5, in
number = int(input_value)
ValueError: invalid literal for int() with base 10: ''
Any suggestions are greatly appreciated!
while True:
input_value = input("Type a number: ")
number = int(input_value)
if input_value.isalpha():
print("Not a number")
break
else:
if input_value is None:
number = int(0)
break
else:
if int(number):
break
print(number)
When a user input is empty, input_value will be "", which python cannot convert to an integer. number = int("") will throw an error.
What you can do is check if the input is equal "" and if it is, set number to 0, else convert it using int().
Better yet, I would wrap number = int(input_value) in a try catch statement:
while True:
input_value = input("Type a number: ")
try:
number = int(input_value)
except:
print("invalid input")
break
So to break the loop, you'd enter something thats not a number. In this case, you'd only be storing the last input value into number, so it's up to you how you want to keep track of all the inputs (probably using a list).
just a thought:
while True:
input_value = input("Type a number: ")
if input_value:
try:
number = int(input_value)
break
except:
continue
print(number)

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")

If statement based on invalid class entered in Python

I'm quite new to python and I'm trying to create a program that uses an if statement that is based on if an int input ( int(input()) ) gets the right input class. For example: if I have an input that goes Var1 = int(input("Enter a number:...")), and the user enters hello there, this would, instead of giving an error message, go into one of the options in an if statement.
Since the rest of the code hasn't been created yet I can't post it, but I've tried all the ways I've come up with to solve this problem without success... Can anyone help me please?
You can surround your input with a try..except block and capture a ValueError that will occur when int() tries to convert a non-integer into an integer:
try:
var1 = int(input("Enter an integer: "))
except ValueError:
print("That's not an integer!")
You can even force your users to enter an integer by placing it in a loop:
var1 = None
while var1 is None:
try:
var1 = int(input("Enter an integer: "))
except ValueError:
print("That's not an integer!")
Or you can do checks at a later time:
var1 = input("Enter an integer: ")
try:
var1 = int(var1)
print("Thank you for entering an integer.")
except ValueError:
print("That's not an integer!")
You can use try/except:
while(True):
try:
var1 = int(input("enter a number: "))
break
except ValueError:
print('it should be a number')
caution: don't use try/except without Execption type like:
try:
printo('hi')
except:
pass
it will except all excetions even syntax error

Checking if input is an integer [duplicate]

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)

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