Python 関数

Programming Functions

関数とは、単一のタスクを実行するために使用される、整理されたコードのブロックです。これらはアプリケーションに優れたモジュール性と再利用性を提供します。

Function Arguments

関数は argumentsreturn values を受け取ることができます。

次の例では、関数 say_hello は引数 “name” を受け取り、挨拶を出力します。

# Define a function that takes one argument
def say_hello(name):
   print(f'Hello {name}')

# Call the function with a string argument
say_hello('Carlos')
Hello Carlos
say_hello('Wanda')
Hello Wanda
say_hello('Rose')
Hello Rose

Keyword Arguments

コードの可読性を向上させるために、できる限り明示的であるべきです。これは、関数内で Keyword Arguments を使用することで実現できます。

# Function with multiple parameters
def say_hi(name, greeting):
   print(f"{greeting} {name}")

# Positional arguments: order matters
say_hi('John', 'Hello')
Hello John
# Keyword arguments: order doesn't matter, more readable
say_hi(name='Anna', greeting='Hi')
Hi Anna
クイズ

ログインしてこのクイズに回答し、学習の進捗を追跡できます

What is the main advantage of using keyword arguments in Python functions?
A. They execute faster
B. They use less memory
C. They improve code readability and order doesn't matter
D. They prevent errors

Return Values

def ステートメントを使用して関数を作成する場合、return ステートメントで返り値を指定できます。return ステートメントは以下で構成されます。

  • return キーワード。

  • 関数が返す値または式。

# Function that returns a value using return statement
def sum_two_numbers(number_1, number_2):
   return number_1 + number_2

# Call function and store the returned value
result = sum_two_numbers(7, 8)
print(result)
15
クイズ

ログインしてこのクイズに回答し、学習の進捗を追跡できます

What keyword is used to return a value from a function in Python?
A. return
B. output
C. yield
D. exit

Local and Global Scope

  • グローバルスコープのコードはローカル変数を使用できません。

  • ただし、ローカルスコープはグローバル変数にアクセスできます。

  • 関数のローカルスコープ内のコードは、他のローカルスコープの変数を使用できません。

  • 異なるスコープにある場合、異なる変数に同じ名前を使用できます。つまり、spam という名前のローカル変数と、同じく spam という名前のグローバル変数が存在し得ます。

# Global variable: accessible everywhere
global_variable = 'I am available everywhere'

def some_function():
    print(global_variable)  # Can access global variable
    # Local variable: only exists within this function
    local_variable = "only available within this function"
    print(local_variable)

# This will raise NameError: local_variable doesn't exist in global scope
print(local_variable)
Traceback (most recent call last):
  File "<stdin>", line 10, in <module>
NameError: name 'local_variable' is not defined

The global Statement

関数内からグローバル変数を変更する必要がある場合は、global ステートメントを使用します。

# Use 'global' keyword to modify global variable from inside function
def spam():
    global eggs  # Declare that we're modifying the global variable
    eggs = 'spam'  # This changes the global variable

eggs = 'global'
spam()  # Function modifies global variable
print(eggs)  # Prints 'spam', not 'global'
spam
クイズ

ログインしてこのクイズに回答し、学習の進捗を追跡できます

What keyword must you use inside a function to modify a global variable?
A. nonlocal
B. global
C. extern
D. No keyword needed

変数がローカルスコープにあるかグローバルスコープにあるかを判断するには、次の 4 つのルールがあります。

  1. 変数がグローバルスコープ(つまり、すべての関数の外側)で使用されている場合、それは常にグローバル変数です。

  2. 関数内にその変数に関するグローバルステートメントがある場合、それはグローバル変数です。

  3. それ以外の場合、関数内でその変数が代入ステートメントで使用されている場合、それはローカル変数です。

  4. ただし、変数が代入ステートメントで使用されていない場合、それはグローバル変数です。

Lambda Functions

Python において、ラムダ関数は単一行の無名関数であり、任意の数の引数を取ることができますが、式は 1 つしか持つことができません。

From the Python 3 Tutorial

lambda は、式の中で使用できる最小限の関数定義です。FunctionDef とは異なり、body は単一のノードを保持します。

Single line expression

ラムダ関数は、単一行のコードのような式のみを評価できます。

この関数:

# Regular function definition
def add(x, y):
    return x + y

add(5, 3)
8

は、ラムダ 関数:

# Lambda function: anonymous function defined in one line
# Syntax: lambda arguments: expression
add = lambda x, y: x + y
add(5, 3)
8

と同等です。

クイズ

ログインしてこのクイズに回答し、学習の進捗を追跡できます

What is a lambda function in Python?
A. A function that can only be called once
B. A function that takes no arguments
C. A function that returns multiple values
D. A single-line anonymous function that can have any number of arguments but only one expression

通常のネストされた関数と同様に、ラムダも辞書式クロージャとして機能します。

# Lambda closure: lambda function that captures variable from outer scope
def make_adder(n):
    return lambda x: x + n  # Lambda captures 'n' from outer function

# Create functions that add different amounts
plus_3 = make_adder(3)  # Returns lambda that adds 3
plus_5 = make_adder(5)  # Returns lambda that adds 5

plus_3(4)  # Returns 4 + 3 = 7
7
plus_5(4)
9
クイズ

ログインしてこのクイズに回答し、学習の進捗を追跡できます

What does a lambda closure allow you to do?
A. Capture variables from the outer scope
B. Modify global variables without the global keyword
C. Return multiple values
D. Execute code asynchronously