[Tutor] if statement problems(noob question)
Dave Angel
davea at davea.name
Mon Apr 8 12:45:59 CEST 2013
On 04/08/2013 06:21 AM, Max Smith wrote:
> Hi, everyone whom might read this, im Max and i am really new to coding,
> been going at it for about two weeks using codeacademy and the book "think
> python".
> when i decided to experiment a little with if statements i ran into the
> following problem:
>
> def plus(x,y):
> if x and y == int or float:
What is it you expect this to do? Have you tried a similar, simpler
expression to get acquainted?
x = 2
if x == int:
will always fail, since the integer 2 is not equal to the type int. In
Python 2.x, when you compare objects of different types, you generally
get unequal. (Exception, if you define your own classes, you can define
how they compare to others) In Python 3, you'd get an exception.
The way you should test an object to see if it's an instance of a class
is to use isinstance()
http://docs.python.org/2/library/functions.html#isinstance
isinstance(x, int)
And if you need to test more than one type or class, use a tuple of the
types:
isinstance(x, (int, float))
Now you can combine more than one such test:
if isinstance(x, (int, float)) and isinstance(y, (int, float)):
--
DaveA
More information about the Tutor
mailing list