Python cannot ignore str when input is int() - python

SO I have a program where the input is in an int, but when the user enters a str, the program crashes. I want the program to ignore any str that it can't convert to an int. I tried declaring a variable that said type(input). Then, I added an if statement:
if (variable) == str:
print(oops)
Remember I declared the input as an int. So I don't know.
Thank you.

You can use exceptions for this. You get a Value Error when you try to convert a string input to int. By enclosing it in a try clause here, it is telling that if a Value Error arises, you can ignore it. For now I've used the pass statement, but if there's something else you want to do if the input is a string, you can add it there.
try:
x = input()
value = int(x)
print(value)
except ValueError:
pass

You can use try-except to handle the case.
try:
value = int(input())
except ValueError:
print("Input is not an int type")
pass

In python you can call isinstance() on the variable passing the datatype you want to check for-
sent = 'your_string'
num = 24
isinstance(sent, int) # returns False
isinstance(num, int) # returns True
isinstance(sent, str) # returns True
isinstance(num, str) # returns False
Applicable with other data types too!
So a simple-
if not isinstance(str, int):
print('Only integer values accepted')

if my_input.isdigit():
int(my_input)
# your code goes here
else:
print('oops')
exit() # maybe you like to exit

You could do something like
input_number = input("Enter your number")
if type(eval(input_number)) == int:
#Do stuff
else:
print('Sorry that is an invalid input')
I also noticed you said
Remeber I declared the input as an int
Python is not statically typed, so you don't have to declare a variable as a certain data type, and along with that even if you do, their type can still be changed.

You can use str.isnumeric() to check if input is of int type or not. THis is better than using try..except
input_number = input("enter a number: ")
if input_number.isnumeric():
input_number = int(input_number)
# do magic

Related

inputs not validated properly

Right now, I am zooming into a section of my code as below :
qty = int(input('enter current quantity :'))
if qty != int:
print('input is not integer')
in the above chunk, i passed '5' yet
it returns 'input is not integer'...
So i tried running the below code:
type(qty)
After running this, the output is 'str'
does anyone know what can I change so that the inputs properly gets converted?
i tried....
#notice how i removed the space between '=' and 'int'
qty =int(input('enter current quantity :'))
if qty != int:
print('input is not integer')
this time, the same message appears... HOWEVER,
type(qty)
returns that it has successfully converted to 'int'
That's not how you check the type of instance of an object.
You should use isinstance function if you care about the inheritance OR use type if you want to check specifically for a type.
Option 1:
x = 5
if isinstance(x, int):
# Do some logic here
Option 2:
x = 5
if type(x) is int: # Use "is" and not "==", since classes are singletons!
# Do some logic here
Regarding your code:
qty = int(input('enter current quantity :'))
if qty != int:
print('input is not integer')
If qty is provided by user and can be casted into an int
the condition is false, cause e.g. 5 is NOT equal class int.
If qty is left blank then an empty string is passed to the int() and ValueError: invalid literal for int() with base 10: '' is raised.
So the condition is NEVER true.
Side notes:
In python it's common to use EAFP (easier ask for forgiveness than for permission) more often than LBYL (look before you leap), so you shouldn't care what is the type, do your logic and handle possible raised errors
python uses ducktyping concept, so if it quacks like a duck and walks like a duck treat it like one (doesn't matter it it actually is a duck or not), more technically if an entity implements a particular interface you don't have to check for its type per se
for more info about type vs isinstance look here What are the differences between type() and isinstance()?
please do read about difference between "==" comparison and "is" operator
if qty != int is not how you check for the type of a variable. Instead, try:
if not isinstance(qty, int):
...
Note, however, that if the user doesn't enter an integer i.e.:
int("hello world")
Then a ValueError will be thrown, meaning the code will never reach your if statement. A better solution is to wrap the user input in a try-except statement

String Check with if Statement in Python

I want to check input is an equal to string or not. But, my code cannot see if statement. I think the problem is in if statement equation:
name = input("Name: ")
if name != str:
print("Please enter letter answer ...")
name = str(input("Name: "))
else:
print(input(name))
I guess I cannot write name != str. But I don't know how to check input is equal to string. ???
First of all, you can't check an input string against a type str. inputs will always be of type str. If you want to check for strings in general, you can use type(var) == str.
input will always return a string, so you don't have to check if it is a string.
Also, this line: print(input(name)) asks for input again, you probably just want print(name)
This code should work just fine for what you would want:
name = input("Name: ")
print(name)
If you want the name to not include any numbers or spaces, so it is just a single name, you can try isalpha():
if name.isalpha():
pass # Do your stuff with the name here
I would recommend using isinstance(object, type) function because it is a boolean function already
for example: if isinstance(name,str):
you can also use the type() function if you want to use an approach more like what you are already using. The type() function can be useful overall
for example:
if type(name) != str:
print("Error; name is ",type(name))
In Python, Whatever you enter as input, the input() function converts it into a string. If you enter an integer value, still it will convert it into a string.
Using isaplha() like #funie200 said:
while True:
name = input("Name: ")
if name.isalpha():
print(name.title)
break
else:
print("Please enter your name...")

Python 3 allowing only one input data type

I want to make this program print "Only str type supported" when 'name' gets any data type that isn't str. What should i change in this code?
while True:
name =(input("Whats ur name?"))
if name == 'Richard':
print('ok')
break
elif name == "gosha":
print('FEUER FREI! "BANG BANG BANG BANG"')
else:
print('denied')
while True:
name =(input("Whats ur name?"))
check = True
for ele in name:
try:
fl = float(ele)
nu = int(ele)
print("Only str type supported")
check = False
except:
pass
if check:
if name == 'Richard':
print('ok')
break
elif name == "gosha":
print('FEUER FREI! "BANG BANG BANG BANG"')
else:
print('denied')
It checks individual characters of the name and tries to convert them to float or int. If a value can be converted, it fails, throws the error and asks for name again
For what i know, all input is a string, but I understand that what you want is to only receive letters and no numbers in the input. In that case, you can check each element of the string to see if they are numbers, and if one is found, return the error message.
To check it you would have to use:
for c in name:
if c.isdigit():
print("Only str type supported")
break
This will iterate through the input string and check if any of the elements on it is a number.
EDIT: you could just use name.isalpha() to check if all the characters are letters. Would be easier to read and eliminates the unnecessary loop.
You can branch on the type of name such as:
if type(name) is not str:
print('Only str type supported')
or
if not isinstance(name, str):
print('Only str type supported')
But as others have pointed out, input() will always return a str.
https://docs.python.org/3/library/functions.html#input
Your current question is hard to answer. The input function will always return a string. That string might be a "1" or at "3.14159" or empty "" but it will always be a string.
When you say you want it to only support string types, maybe you mean you want to check if the given input can be converted to an int, a float, or is empty?
If that's the case use try and except and rely on the cast to int or float failing to "prove" it's a string by eliminating it's ability to be a different type.
Add additional type checks as needed to make your logic more robust.
Do something like this:
while True:
name = input("Whats ur name? ")
try:
float(name)
int(name)
print("I only support strings that are names")
break
except ValueError:
pass
print("It's not a float or an int so it's a string!")

how to tkinter Entry widget .get() compare with int?

I want to accept data from the user in int format..but the .get() method returns a str object.
using IntVar also is not helping. the following is somewhat what i want to do:
inp = Entry(master)
#some code here
num = inp.get()
if num >5:
#do something
Entry.get() returns a string. use int to convert the string into an integer.
if int(num) >5: #do something
Of course, this may raise an Exception if the string can't be converted to an integer. For example, if the user enters "Hello" instead of a number, or just doesn't write anything at all.

how do i fix a "NameError: name 'thing' is not defined" when calling a function ?

i am learning python from code academy, and i'm trying to complete their review assignment.
I am supposed to define a function, and then set up a if/else loop to check the type of input i get, and then return either absolute value of an int/float or an error message.
I tried to look at similar questions, but i don't understand those codes are a lot more complicated than i can understand O_O. I looked at the function module lessons again, but i think i followed the function making pattern correctly ? Is there supposed to be an extra line before i call the function ? I tried to keep going, but then i am gettnig this same error message in the other exercises.
I would appreciate any responses :)
def distance_from_zero(thing):
thing = input
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
distance_from_zero(thing)
Are you trying to use the input function to get a value from the user ?
if so, you must add parenthesis to it:
thing = input()
# If you're using python 2.X, you should use raw_input instead:
# thing = raw_input()
Also, you don't need the input parameter if that's what you're trying to do.
If you do mean input to be a parameter, then you're trying to use variables before defining them. distance_from_zero(thing) can't work since thing hasn't been defined outside your function, so you should either define that variable first or call it with a litteral value:
thing = 42
distance_from_zero(thing)
# or
distance_from_zero(42)
thing isn't defined when you pass it to the distance_from_zero function?
def distance_from_zero(input):
if type(input) != int or float:
return "Not an integer or float!"
else:
return abs(input)
thing = 5
distance_from_zero(thing)
You do not define the thing. Please try
def distance_from_zero(thing):
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
thing = 1
distance_from_zero(thing)
Or your meaning is this, accepting the user input?
def distance_from_zero():
thing = int(input())
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
distance_from_zero()
And your code if type(thing) != int or float: will always go to True for it is if (type(thing) != int) or float. Change it to if not isinstance(thing, (int, float)):.

Categories