⑦Pythonプログラミング

Pythonの関数の定義と活用方法【引数・戻り値・ラムダ完全ガイド】

⑦Pythonプログラミング
記事内に広告が含まれています。

Pythonの関数を使えばコードを再利用できます。引数・戻り値・デフォルト値・可変長引数など、Pythonの関数の書き方を詳しく解説します。

関数の基本

def greet(name):
    return f"こんにちは、{name}さん!"

message = greet("Taro")
print(message)  # こんにちは、Taroさん!

デフォルト引数とキーワード引数

def power(base, exponent=2):
    return base ** exponent

print(power(3))      # 9(exponent=2がデフォルト)
print(power(2, 10))  # 1024
print(power(exponent=3, base=4))  # 64(キーワード引数)

可変長引数

# *args: 複数の位置引数をタプルで受け取る
def total(*args):
    return sum(args)

print(total(1, 2, 3, 4, 5))  # 15

# **kwargs: 複数のキーワード引数を辞書で受け取る
def profile(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

profile(name="Taro", age=25, city="Tokyo")

ラムダ関数

# 1行で書ける無名関数
square = lambda x: x ** 2
print(square(5))  # 25

# sortのkeyによく使う
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort(key=lambda x: -x)  # 降順
print(numbers)  # [9, 5, 4, 3, 1, 1]

まとめ

  • defキーワードで関数を定義し、returnで値を返す
  • デフォルト引数で省略可能な引数を設定できる
  • *argsで可変長の位置引数、**kwargsでキーワード引数を受け取れる
  • ラムダ関数で1行の無名関数を定義できる

コメント

タイトルとURLをコピーしました