Skip to main content

Conditions and Branching

Conditions​

Comparison​

i = 1
print(i >= 7) # greater or equals
Output
False
i = 12
print(i != 10)
# != means "not equals"
# -> it's true that 12 isn't = 10
Output
True
  • this goes the same to strings
print("kevin" == "ph4n") # this a false
print("kevin" != "ph4n") # this a true
Output
False
True

Branching​

if​

age = 18
if age > 21:
print("you may drink alcohol")

print("keep it going")

# -> if the statement is False -> it passes to the next
Output
keep it going

else​

age = 18
if age > 21:
print("you may drink alcohol")
else:
print("get out")

print("keep it going")

# the system checks if the "if (age > 21)" is true or false -> processes the else
# whether if the if condition is true or false, "keep it going" will still be there
Output
get out
keep it going
age = 22
if age > 21:
print("you may drink alcohol")
else:
print("get out")

print("keep it going")
Output
you may drink alcohol
keep it going

elif (short for else if)​

age = 21
if age > 21:
print("you may drink alcohol")
elif age == 21:
print("you may drink it...only this time okay?")
else:
print("get out")

print("keep it going")
Output
you may drink it...only this time okay?
keep it going

Logic Operators​

or​

ABA or B
FalseFalseFalse
FalseTrueTrue
TrueTrueTrue
born_year = 2008
if (born_year < 2000) or (born_year > 2009):
print("kevinph4n was born in the 90s or 2010s")
else:
print("kevinph4n was born in 2000s")
Output
kevinph4n was born in 2000s

and​

ABA and B
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue
born_year = 2008
if (born_year > 2007) and (born_year < 2009):
print("kevinph4n was born in 2008")
Output
kevinph4n was born in 2008