learn_note/python/4.more control flow tools.md

2.2 KiB
Raw Permalink Blame History

4.1 if statements

4.2 for statements

4.3 range() function

4.4 break and continue statements, and else clauses on loops

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        # 如果运行了break就不会运行这里
        print(n, 'is a prime number')

4.5 pass statements

4.6 match statements

基本情况

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _: # 下划线代表default
            return "Something's wrong with the internet"

结合

case 401 | 403 | 404: # | 也可以用 or 代替
    return "Not allowed"

tuple匹配

match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y={y}")
    case (x, 0):
        print(f"X={x}")
    case (x, y):
        print(f"X={x}, Y={y}")
    case _:
        raise ValueError("Not a point")

object匹配

class Point:
    x: int
    y: int

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")

模式可以任意嵌套

match points:
    case []:
        print("No points")
    case [Point(0, 0)]:
        print("The origin")
    case [Point(x, y)]:
        print(f"Single point {x}, {y}")
    case [Point(0, y1), Point(0, y2)]:
        print(f"Two on the Y axis at {y1}, {y2}")
    case _:
        print("Something else")

模式里加if

match point:
    case Point(x, y) if x == y:
        print(f"Y=X at {x}")
    case Point(x, y):
        print(f"Not on the diagonal")

4.7 defining functions

4.8 more on defining fucntions

4.8.3 special parameters

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): pos1, pos2 ---- positional only pos_or_kwd ---- positional or keyword kwd1, kwd2 ---- keyword only