Python Programming

Functions and Modules

35 分

Defining functions

def greet(name, greeting="Hello"):
    """Return a greeting for name."""
    return f"{greeting}, {name}!"

greet("Ada")                     # positional
greet(name="Ada", greeting="Hi") # keyword

A function without return returns None.

Flexible arguments

def total(*prices, tax=0.0):
    return sum(prices) * (1 + tax)

total(10, 20, 5, tax=0.2)

def create_user(email, **extra):
    return {"email": email, **extra}

create_user("ada@example.com", role="admin", active=True)

Never use a mutable default: def add(item, items=[]) shares one list across calls. Use items=None then items = items or [].

Type hints

def apply_discount(price: float, percent: int = 10) -> float:
    return price * (100 - percent) / 100

Hints do not change how code runs, but editors and tools like mypy use them to catch mistakes.

Scope

Variables created inside a function are local. Prefer passing values in and returning results out over modifying globals.

Lambdas and functions as values

users.sort(key=lambda u: u["points"], reverse=True)

def shout(text): return text.upper()
handlers = {"shout": shout, "quiet": str.lower}
handlers["shout"]("hi")

Modules and imports

Any .py file is a module.

myapp/
├── main.py
└── billing/
    ├── __init__.py
    └── invoices.py
# main.py
from billing.invoices import create_invoice
import billing.invoices as inv

The main guard

def main():
    print("running")

if __name__ == "__main__":
    main()

Code under the guard runs when the file is executed, not when it is imported, so modules can be both scripts and libraries.

The standard library

Learn what is already included before installing packages: pathlib, datetime, json, csv, re, random, statistics, itertools, functools, logging, argparse, subprocess, urllib.

Exercise

Create a package shop/ with pricing.py (functions for subtotal, tax, discount with type hints and docstrings) and a main.py that imports them and prints a receipt.

Check yourself

  • What goes wrong with def f(items=[])?
  • What does if __name__ == "__main__": achieve?
  • What is the difference between *args and **kwargs?

進捗はこのブラウザーにのみ保存されます。

レビューに提出(10 ポイント)