2

Python3: I wish to know if I can set up an if statement to execute some code just like one normally would.

But I want the statement to go something like this: (psudo-code)

If variable1 !== "variable type integer":
    then break. 

Is this possible? Thanks for the help.

I apologize if this has already been addressed, but the search suggester bot didn't have any posts to point me to.

Jesse, NOOb

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
11thZone
  • 71
  • 3
  • 10

2 Answers2

4

Usually it's better to use isinstance, so you accept variables that quack like ducks, too:

>>> isinstance(3.14, int)
False
>>> isinstance(4, int)
True
>>> class foo(int):
...     def bar(self):
...         pass
... 
>>> f = foo()
>>> isinstance(f, int)
True
tomclegg
  • 485
  • 3
  • 4
0

You can import the types and check variables against them:

>>> from types import *

>>> answer = 42

>>> pi = 3.14159

>>> type(answer) is int # IntType for Python2
True

>>> type(pi) is int
False

>>> type(pi) is float # FloatType for Python 2
True

For your more specific case, you would use something like:

if type(variable1) is int:
    print "It's an int"
else:
    print "It isn't"

Just keep in mind that this is for a variable that already exists as the correct type.

If, as you may be indicating in your comment (if user_input !== "input that is numeric"), your intent is to try and figure out whether what a user entered is valid for a given type, you should try a different way, something along the lines of:

xstr = "123.4"             # would use input() usually.
try:
    int(xstr)              # or float(xstr)
except ValueError:
    print ('not int')      # or 'not float'
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • isnt pi a float type? And if I understand you correctly, this is pulling from a "types" module? Basically I just need a way of executing a break statement by using an if. if user_input !== "input that is numeric" – 11thZone Feb 09 '15 at 06:02
  • @user3321476, yes, it's a float type, which is why `type(pi) is int` gave you false. I've added the Python3-specific ones, relegating Python2 to comments, and given a more concrete example for you at the bottom. – paxdiablo Feb 09 '15 at 06:04
  • sweet, i get it now, you rock! – 11thZone Feb 09 '15 at 06:07
  • @user3321476, hopefully, I'll rock enough to get an upvote and/or accept. Nudge nudge, wink, wink :-) – paxdiablo Feb 09 '15 at 06:17