0

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'

  • If the call to *int()* was successful then *qty* is guaranteed to be of type int. You are trying to compare an integer value with a type. They will never be equal – DarkKnight Feb 04 '23 at 11:35

2 Answers2

1

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
Gameplay
  • 1,142
  • 1
  • 4
  • 16
0

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

Mouse
  • 395
  • 1
  • 7