In [ ]:
x = 5
print(x > 2)
In [ ]:
x = 5
print(x < 2)
x < y
tests whether $x$ is smaller than $y$. True
or False
.
In [1]:
x = 20
print (x > 2)
In [2]:
# one way
x = 1
print (x > 2)
# another way
x = 20
print (x < 2)
In [ ]:
x = 5
if x > 2:
print(x)
In [ ]:
x = 0
if x > 2:
print(x)
In [ ]:
x = 0
if x > 2:
print(x)
print("hello")
if
takes something that can be interpreted True
or False
and then executes only if that something is True
. if
executes conditionally; anything not indented under the if
runs no matter what.
In [ ]:
x = 20
if x < 5:
print(x)
In [ ]:
# one way
x = 2
if x < 5:
print(x)
# another way
x = 20
if x < 100:
print(x)
In [ ]:
x = 100
if x > 100:
print(x)
In [ ]:
x = 2
if x < 5 and x > 10:
print("condition met")
In [ ]:
x = 2
if x < 5 or x > 10:
print("condition met")
In [ ]:
x = 2
if not x > 5:
print("condition met")
and
" and "or
" let you logically concatenate True
and False
statements. not
" lets you invert the logic of a True
or False
statement.
In [ ]:
x = 20
if x < 5 or x > 10:
print("HERE")
In [ ]:
#answer
x = 20
if x > 16 and x < 23:
print("HERE")
In [ ]:
if x < 0 or x > 10:
print(x)
In [ ]:
x = 5
if x > 2:
print("inside conditional")
print("also inside conditional")
if x < 2:
print("inside a different conditional")
print("not inside conditional")
Python decides what is inside the conditional if
using indentation.
In [ ]:
x = 5
if x > 10:
print("condition 1")
else:
print("condition 2")
The else
statement executes if the condition is not met.
In [ ]:
x = 1
if x > 1:
print("condition 1")
elif x == 1:
print("condition 2")
else:
print("condition 3")
In [ ]:
x = -2
if x > 5:
print("a")
elif x > 0 and x <= 5:
print("b")
elif x > -6 and x <= 0:
print("c")
else:
print("d")
elif
is a way to test another conditional in the same block.
In python the:
if CONDITION:
DO_SOMETHING
elif SOME_OTHER_CONDITION:
DO_SOMETHING_ELSE
elif YET_ANOTHER_CONDITION:
DO_YET_ANOTHER_THING
else:
DO_WHATEVER_WE_WANT
construct allows different responses in response to different conditions. If no conditions are met, whatever is under else
is done. If multiple conditions are met, only the first condition is met.
In [ ]:
x = 5
if x > 10:
print("condition 1")
elif x < 0:
print("condition 2")
else:
print("condition 3")
In [ ]:
if x < 0:
print("a")
elif x == 0:
print("b")
else:
print("c")
You can build more complex conditions using and
, or
, and not
.
For example:
x > 10 and x < 20
# Even more complicated
x > 20 and not (x > 22)
if CONDITION:
DO_SOMETHING
elif SOME_OTHER_CONDITION:
DO_SOMETHING_ELSE
elif YET_ANOTHER_CONDITION:
DO_YET_ANOTHER_THING
else:
DO_WHATEVER_WE_WANT
construct allows different responses in response to different conditions. If no conditions are met, whatever is under else
is done. If multiple conditions are met, only the first condition is met.