Aug 22, 2024
Presented by David Malan
Focus: Conditionals in Python, making decisions in code.
>
>=
<
<=
==
(two equal signs)!=
if
keyword to ask questions.if condition:
# code to execute
if X < Y:
print("X is less than Y")
elif X > Y:
print("X is greater than Y")
else:
print("X is equal to Y")
elif
to chain conditions logically:
if X < Y:
# ...
elif X > Y:
# ...
else:
# ...
else
provides a catch-all for when all previous conditions are false.X = int(input("What's X? "))
Y = int(input("What's Y? "))
if X < Y:
print("X is less than Y")
elif X > Y:
print("X is greater than Y")
else:
print("X is equal to Y")
and
, or
to combine conditions:
if (X > 90 and X <= 100):
print("A")
elif (X > 80 and X < 90):
print("B")
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
def is_even(n):
return n % 2 == 0
match
Statementmatch
statement as a more compact alternative to multiple if
conditions:
match name:
case "Harry":
print("Gryffindor")
case "Hermione":
print("Gryffindor")
case "Ron":
print("Gryffindor")
case "Draco":
print("Slytherin")
case _: # catch-all
print("Who?")
if
, elif
, else
, and now match
to structure your code effectively.