# Python Conditionals¶

• Keywords
• if
• elif
• else
• Conditionals
• ==, !=, <, <=, >, >=, and, or, not
• Keywords: True and False

Examples

In [1]:
x = 5.5

In [2]:
if x < 10:                  # note the ":"
print("x < 10")

x < 10

In [138]:
if x < 3 :
print("x < 3")
else :                      # note the "else"
print("x >= 3")

x >= 3

In [139]:
if x < 3 :
print("x < 3")
elif x < 4 :                # note the "elif"
print("x < 4")

In [140]:
if x < 3 :
print("x < 3")
elif x < 4 :
print("x < 4")
else:                       # else to cap it off
print("x >= 4")

x >= 4

In [141]:
if x < 3 :
print("x<3")
elif x < 5 :               # multiple elif
print("x<5")
elif x > 5 :
print("x>5")
else :
print("something else")

x>5

In [2]:
x = 5.5

if (x > 3 and x < 6) or x <= 1 :

print("Doing some more stuff in here")

print("Can have multiple lines. ")
print("Blank lines don't matter.")        # note the use of the single and double quotes
print("Indent all lines inside the block at the same level")

made it
Doing some more stuff in here
Can have multiple lines.
Blank lines don't matter.
Indent all lines inside the block at the same level


Can use variables or expressions in if statements

In [2]:
Tmin = 298.15
T    = 500

if T < Tmin :
print("Warning, T<Tmin")

if T > Tmin*10 :
print("Warning, T>10*Tmin")

if Tmin <= T and T <= 10*Tmin:
print("All is well with T, nice work.")


All is well with T, nice work.


Scope: variables declared outside the if statement can be seen inside.

In [3]:
Tmin = 298.15
T    = 500

if T> Tmin:
print("T =", T)

T = 500


Here is a condensed if statement:

In [5]:
T = 298.15 if x<5.0 else 500.0              # single line if statement

print("x=", x, ", T=", T)# note: sep='' changes the separation character

x= 5.5 , T= 500.0


Example

Take the the square root, and make the argument positive if its negative:

In [145]:
x = -9
print(x**0.5)

y = (x if x>=0 else -x)**0.5
print("y = ", y)

(1.8369701987210297e-16+3j)
y =  3.0