Menu
Coddy logo textTech

デフォルト値

CoddyのPythonジャーニー「Fundamentals」セクションの一部 — レッスン 48/77。

関数を作成する際、あらかじめ決められたデフォルト値を持つオプションの引数を持たせたい場合があります。例:
def greet(name, greeting="Hello"):
    print(name, greeting)
必須の引数のみを使用して関数を呼び出す場合:
greet("John")
# Output: John Hello
両方の引数を指定して関数を使用する場合:
greet("john", "welcome")
# Output: john welcome
デフォルト値を持つ複数の引数を定義することもできます:
def describe_person(name, age=25, city="Unknown"):
    print(f"{name} is {age} years old and lives in {city}")
describe_person("Alice")
# Uses both defaults

describe_person("Bob", 30)
# Uses default city

describe_person("Charlie", 35, "New York")
# Uses no defaults
重要なルール: デフォルト引数は、関数定義においてデフォルト値を持たない引数の後に配置する必要があります。
# Correct:
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")
# Incorrect:
def greet(greeting="Hello", name):
    print(f"{greeting}, {name}!")

自分で試してみよう

このレッスンにはコードチャレンジは含まれていません。

quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Fundamentalsのすべてのレッスン