リリース・改善中
Python ガイド · 2/6
この章は現在、英語でのみ提供しています。
Python's syntax is famously compact, but a few of its rules surprise newcomers from brace-based languages. This chapter walks through variables, indentation, functions and their flexible argument handling, control flow, and f-strings, the everyday way to build text.
There is no declaration keyword: a variable comes into existence the first time you assign to it. Think of a variable as a label attached to a value. The value has a type; the label does not, so the same name can later point at something of a different type.
count = 3
name = "Python"
pi = 3.14159
is_ready = True
# assign several names at once, then swap them
x, y = 1, 2
x, y = y, x
# convention: snake_case for variables and functions, UPPER_CASE for constants
MAX_RETRIES = 5Most projects follow the PEP 8 style guide: snake_case for functions and variables, PascalCase for classes, and UPPER_CASE for module-level constants.
Instead of braces, Python uses indentation. Statements that open a block, such as if, for, def and class, end with a colon, and every line indented beneath them at the same depth belongs to that block. Four spaces per level is the standard. Mixing tabs and spaces causes errors, so configure your editor to insert spaces. Comments start with #, and a triple-quoted string placed directly under a function or class becomes its docstring, which help() and editors display as documentation.
Define functions with def and hand back a result with return; a function that never returns explicitly gives back None. Parameters can have defaults, and callers may pass arguments by name, which makes call sites self-documenting.
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
greet("Mina") # 'Hello, Mina!'
greet("Mina", greeting="Hi") # 'Hi, Mina!'
greet(greeting="Hey", name="Joon") # 'Hey, Joon!'When a function should accept a variable number of arguments, use *args to collect extra positional arguments into a tuple and **kwargs to collect extra keyword arguments into a dict. A bare * in the parameter list makes everything after it keyword-only.
def log(message, *args, level="INFO", **kwargs):
print(level, message, args, kwargs)
log("start", 1, 2, user="kim")
# INFO start (1, 2) {'user': 'kim'}
def connect(host, *, timeout=10):
...
connect("db.local", timeout=5) # timeout can only be passed by nameOne classic trap: default values are evaluated once, when the function is defined. Writing def add(item, items=[]) means every call shares the same list. Use None as the default and create a fresh list inside the function instead.
Branching uses if, elif and else. Boolean operators are spelled out as words: and, or, not. There are two loops: while, and for, which walks over anything iterable, including lists, strings, dicts, files and ranges.
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
for i in range(3): # 0, 1, 2
print(i)
fruits = ["apple", "banana"]
for index, fruit in enumerate(fruits):
print(index, fruit)
n = 10
while n > 0:
n -= 3
if n == 4:
continue
print(n)break leaves a loop early and continue skips to the next iteration. For a compact choice between two values there is the conditional expression, "even" if n % 2 == 0 else "odd". When you need to branch on the shape of a value, the match statement offers structural pattern matching.
Prefix a string literal with f and you can embed variables and arbitrary expressions in braces. A format spec after a colon controls decimals, width, alignment and thousands separators, and a trailing = prints both the expression and its value, which is great for quick debugging.
name = "Mina"
price = 12345.678
print(f"Hi {name}, your total is ${price:,.2f}") # 12,345.68
print(f"{name:>10}|") # right-aligned in a field of 10
print(f"{len(name) * 2}") # any expression works
print(f"{price=}") # price=12345.678*args and **kwargs; never use a mutable object as a default.if/elif/else, for and while for control flow, and f-strings for building text.
コメント 0件
ログイン · ログインするとコメントできます。
最初のコメントを書いてみましょう。