= 15
temp
if temp > 30:
print("Too hot")
elif temp > 20:
print("It's about right")
else:
print("It's cold")
print("Bye!")
It's cold
Bye!
if
elif
else
Structure= 15
temp
if temp > 30:
print("Too hot")
elif temp > 20:
print("It's about right")
else:
print("It's cold")
print("Bye!")
It's cold
Bye!
This is long
= 4
score
if score >= 5:
= "pass"
msg else:
= "fail"
msg
print(msg)
fail
use Ternary Operator instead
if condition else value_if_false value_if_true
= 7
score
= "pass" if score >= 5 else "fail"
msg msg
'pass'
and
or
not
they can be short-circuited.
= True
high_income = False
good_credit = False
student
if (high_income or good_credit) and not student:
print("eligible")
else:
print("not eligible")
eligible
= 23
age
if 18 < age < 60:
print("eligible")
eligible
match
statement (Pattern matching)Implemented in Python 3.10
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
400)
http_error(418)
http_error(0) http_error(
"Something's wrong with the internet"
def http_error2(status):
match status:
case 400:
return "Bad request"
case 401 | 403 | 404: # combine
return "Not allowed"
case _:
return "Something's wrong with the internet"
401)
http_error2(403) http_error2(
'Not allowed'
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def where_is(point):
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print(f"Y={y}")
case Point(x=x, y=0):
print(f"X={x}")
case Point():
print("Somewhere else")
case _:
print("Not a point")
= Point(0, 0)
p0 where_is(p0)
Origin
= Point(1, 1)
p1 where_is(p1)
Somewhere else
= [200, 300, 404, 500]
today_responses match today_responses:
case [a]:print(f"One response today: {a}")
case [a, b]:print(f"Two responses today: {a} and {b}")
*rest]:
case [a, b, print(f"All responses: {a}, {b}, {rest}")
All responses: 200, 300, [404, 500]
__match_args__
class Point:
__match_args__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
# Suppose you have an instance of Point
= Point(1, 2) point
You can use pattern matching to destructure the point:
match point:
case Point(x, y):
print(f"The point is at ({x}, {y}).")
The point is at (1, 2).
Is equivalent to:
if isinstance(point, Point):
print(f"The point is at ({point.x}, {point.y}).")
The point is at (1, 2).
In this example, the match statement checks if point is an instance of Point and then automatically unpacks its x and y attributes according to the order specified in __match_args__
.
def handle_float(x: float) -> None:
print("x is float")
def handle_list(x: list) -> None:
print("x is list")
def num_or_list(x: float | list) -> None:
= {
type_handler float: handle_float,
list: handle_list,
}= type_handler.get(type(x))
handler if handler:
handler(x)else:
print("Unsupported type")
2.1) num_or_list(
x is float
"x", "y"]) num_or_list([
x is list