Python: Conditional. if then else

By Xah Lee. Date: . Last updated: .

If statement

x = 1
if x == 1:
    print("yes")

If else

y = 2

if y == 1:
    print("yes")
else:
    print("no")

The pass statement

The pass statement does nothing.

y = 2

if y == 2:
    pass
else:
    print("no")

Else if chain

z = 2
if z < 0:
    print("neg")
elif z == 0:
    print("zero")
elif z == 1:
    print("one")
else:
    print("other")

If expression

result = "yes" if 3 > 0 else "no"
print(result)
# yes
result = (1 if 3 > 0 else 0) + 1
print(result)
# 2