MENU

4-05 関数の作成

学習目標

  • 関数の定義と呼び出しができる
  • 引数(パラメータ)を理解し使える
  • 戻り値(return文)を理解し使える
  • 関数を使ったプログラムの整理ができる
  • 実践的な関数を作成できる

前回の復習

前回学んだ内容を簡単に確認しましょう:

# List operations
fruits = ["apple", "banana", "orange"]
fruits.append("grape")
print(fruits[0])

# Dictionary operations
student = {"name": "Taro", "age": 17}
print(student["name"])

復習問題:3人の学生の名前と点数を辞書のリストで管理し、平均点を計算してみよう

解答例
students = [
    {"name": "Tanaka Taro","score":85},
    {"name": "Yamada Hanako","score":70},
    {"name": "Kitagawa Masahiko","score":40}
]

total_score = 0
student_number = 0

for student in students:
    print(f"Name:{student["name"]},Score:{student["score"]}")
    total_score = total_score + student["score"]
    student_number = student_number +1

average = total_score / student_number

print( f"\nAverage Score: {average}")

1. 関数とは

関数は、特定の処理をまとめて名前をつけたものです。同じ処理を何度も書く代わりに、関数として定義しておけば繰り返し使えます。

なぜ関数が必要?

# Without functions - repetitive code
print("=== Student 1 ===")
name1 = "Taro"
score1 = 85
if score1 >= 80:
    grade1 = "A"
elif score1 >= 70:
    grade1 = "B"
else:
    grade1 = "C"
print(f"{name1}: {score1} points, Grade {grade1}")

print("=== Student 2 ===")
name2 = "Hanako"
score2 = 92
if score2 >= 80:
    grade2 = "A"
elif score2 >= 70:
    grade2 = "B"
else:
    grade2 = "C"
print(f"{name2}: {score2} points, Grade {grade2}")

# This is repetitive and hard to maintain!

問題点:

  • 同じ処理を何度も書いている
  • 修正する時に複数箇所を変更する必要がある
  • コードが長くなって読みにくい

2. 関数の基本的な定義

最も簡単な関数

# Define a function
def say_hello():
    print("Hello, World!")
    print("Welcome to Python!")

# Call the function
say_hello()
print("---")
say_hello()  # Can call multiple times

関数の構造:

  • def:関数を定義するキーワード
  • 関数名():関数の名前と括弧
  • ::コロンで定義開始を示す
  • インデント:関数の中身(処理内容)

実習1:自己紹介をする関数を作って、何度か呼び出してみよう


3. 引数(パラメータ)のある関数

引数を使うと、関数に値を渡して処理を変えることができます。

基本的な引数

# Function with one parameter
def greet(name):
    print(f"Hello, {name}!")
    print("Nice to meet you!")

# Call with different arguments
greet("Taro")
greet("Hanako")
greet("Jiro")

f文字列(Format文字列)について:

  • f"Hello, {name}!"fは「f文字列」を表す
  • fは文字列の直前に書く必要がある(print(f"...")
  • {}の中に変数を直接書くことができる
  • 従来の方法:"Hello, " + name + "!"
  • f文字列の方が読みやすく、書きやすい

複数の引数

# Function with multiple parameters
def introduce(name, age, hobby):
    print(f"My name is {name}")
    print(f"I am {age} years old")
    print(f"My hobby is {hobby}")

# Call the function
introduce("Taro", 17, "tennis")
introduce("Hanako", 16, "reading")

実習2:2つの数値を受け取って、四則演算の結果を表示する関数を作ってみよう

解答例
def culculate(a,b):
    print(f"{a}+{b}={a+b}")
    print(f"{a}-{b}={a-b}")
    print(f"{a}×{b}={a*b}")
    print(f"{a}÷{b}={a/b}")

culculate(13,6)

4. 戻り値(return文)

関数は定義よりも後の行で、returnというコマンドを書くと、処理結果を呼び出して、他の変数に渡すことができます。これを「戻り値」と呼びます。「戻り値」は計算結果などを次に活用する際に必要です。

return文の基本

# Function that returns a value
def add_numbers(a, b):
    result = a + b
    return result

# Use the return value
sum1 = add_numbers(5, 3)
print("5 + 3 =", sum1)

sum2 = add_numbers(10, 20)
print("10 + 20 =", sum2)

# Can use directly in expressions
total = add_numbers(15, 25) + add_numbers(10, 5)
print("Total:", total)

より実践的な例

# Function to calculate grade
def calculate_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

# Use the function
students = [
    {"name": "Taro", "score": 85},
    {"name": "Hanako", "score": 92},
    {"name": "Jiro", "score": 78}
]

for student in students:
    grade = calculate_grade(student["score"])
    print(f"{student['name']}: {student['score']} points, Grade {grade}")

実習3:BMIを計算して、判定結果を返す関数を作ってみよう

BMI計算式:BMI = Weight (kg) ÷ (Height (m) × Height (m))

判定基準

  • Below 18.5: Underweight
  • 18.5 or above but below 25: Normal
  • 25 or above but below 30: Overweight (Mild)
  • 30 or above: Obesity (Severe)

テスト用データ

students = [
    {"name":"Taro","height":1.70,"weight":65},
    {"name":"Hanako","height":1.60,"weight":50},
    {"name":"Jiro","height":1.75,"weight":80},
    {"name":"Kintaro","height":1.50,"weight":80}
]
解答例
def bmi(height,weight):
    bmi_score = weight / (height * height)
    
    if bmi_score < 18.5:
        return "Underweight"
    elif bmi_score < 25:
        return "Normal"
    elif bmi_score < 30:
        return "Overweight (Mild)"
    else:
        return "Obesity (Severe)"
    
students = [
    {"name":"Taro","height":1.70,"weight":65},
    {"name":"Hanako","height":1.60,"weight":50},
    {"name":"Jiro","height":1.75,"weight":80},
    {"name":"Kintaro","height":1.50,"weight":80}
]

for student in students:
    comment = bmi(student["height"],student["weight"])
    print(f"{student["name"]}:{comment}")
 

5. デフォルト引数

引数にデフォルト値を設定することができます。下の例では”greeting”に”Hello”をデフォルト値とし、入力されたデータで”greeting”のデータが欠けていればデフォルト値を当てはめます。

# Function with default parameter
def greet_user(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

# Call with different ways
greet_user("Taro")                    # Uses default greeting
greet_user("Hanako", "Good morning")  # Uses custom greeting
greet_user("Jiro", "Hi")              # Uses custom greeting

成績表示の例

# Function to format score display
def display_score(name, score, show_grade=True):
    print(f"Student: {name}")
    print(f"Score: {score}")
    
    if show_grade:
        if score >= 80:
            grade = "A"
        elif score >= 70:
            grade = "B"
        else:
            grade = "C"
        print(f"Grade: {grade}")
    print("---")

# Different usage
display_score("Taro", 85)              # Shows grade
display_score("Hanako", 92, True)      # Shows grade
display_score("Jiro", 78, False)       # No grade

if show_grade:について:

  • 重要if文の後には必ずコロン(:)が必要
  • show_gradeがTrueの場合のみグレード計算・表示を行う
  • Falseの場合はグレード表示をスキップする
  • これにより表示内容を選択できる

実習4:挨拶メッセージをカスタマイズできる関数を作ってみよう

作成例

  • 関数名:custom_greeting(name, time="morning")
  • 朝:”Good morning”、昼:”Good afternoon”、夜:”Good evening”
  • デフォルトは朝の挨拶
  • 使用例:
    • custom_greeting("Taro") → “Good morning, Taro!”
    • custom_greeting("Hanako", "evening") → “Good evening, Hanako!”

6. 課題

課題4:温度変換プログラム

以下の機能を持つ関数を作ってください:

  • 摂氏から華氏への変換 ( $F=C \times \frac{9}{5}+32$ )
  • 華氏から摂氏への変換 ( $C=(F-32) \times \frac{5}{9} $)
  • メニュー形式でユーザーが選択できる

課題5:図形の面積計算プログラム

以下の図形の面積を計算する関数を作ってください:

  • 長方形:rectangle_area(width, height)
  • 円:circle_area(radius)
  • 三角形:triangle_area(base, height)

課題6:数学関数プログラム

以下の数学計算を行う関数を作ってください:

  • 階乗計算:factorial(n) (例:5! = 5×4×3×2×1)
  • べき乗計算:power(base, exponent)
  • 平均計算:average(numbers) (リストを引数にとる)

ヒント

  • 階乗はfor文やwhile文を使って計算
  • べき乗は演算子またはfor文で計算
  • 平均はsum()関数とlen()関数を活用

まとめ

今日学んだこと:

  • 関数の定義defを使った関数の作成
  • 引数:関数にデータを渡す方法
  • 戻り値returnを使った結果の返却
  • デフォルト引数:省略可能な引数の設定
  • プログラムの整理:関数を使ったコードの構造化
  • 実践的な応用:複雑なプログラムの関数による分割

次回は、総合演習として、これまで学んだ全ての知識を使った実践的なプロジェクトに取り組みます。

コメント

コメントする