HomeBooks

En

Chapter 1
§1.0 Running Python
Chapter 3
§3.0 Advanced
§3.1 How to Use Functions
KM
bykarutt

2025-06-03

What is a Function?

When writing programs, you often have to write the same kind of process many times. For example, if you want to display "Hello, ○○!" many times, it's a pain to write the same code over and over.

That's where "functions" come in handy!

What is a Function?

  • Overview: A way to give a name to a process you use often, so you can reuse it as much as you want
  • What You Can Do:
    • Write the same process in a shorter way
    • Make fewer mistakes
    • Make your program easier to read

A function is like a "recipe." Once you make it, you can use it to make the same dish (process) any time.

Basic Way to Write a Function

1. Define a Function

def greet():
    print("Hello!")
    print("Let's do our best today!")
  • def: Means "I'm about to make a function"
  • greet(): The function's name (you can choose any name)
  • :: Shows where the function's contents start
  • Indent: Always indent the contents of a function

2. Use (Call) a Function

# Call the function
greet()

Try it out:

def greet():
    print("Hello!")
    print("Let's do our best today!")

# Use the function
greet()
greet()
greet()

Result:

Hello!
Let's do our best today!
Hello!
Let's do our best today!
Hello!
Let's do our best today!

Using Arguments

You can make functions more useful by passing data to them. This is called an "argument."

Greeting Function with a Name

def greet_person(name):
    print(f"Hello, {name}!")
    print("Let's do our best today!")

# Try it out
greet_person("Taro")
greet_person("Hanako")
greet_person("Sensei")

Result:

Hello, Taro!
Let's do our best today!
Hello, Hanako!
Let's do our best today!
Hello, Sensei!
Let's do our best today!

Using Multiple Arguments

def introduce(name, age, hobby):
    print(f"My name is {name}.")
    print(f"I am {age} years old.")
    print(f"My favorite thing is {hobby}.")

# Try it out
introduce("Taro", 14, "soccer")
introduce("Hanako", 13, "reading")

Result:

My name is Taro.
I am 14 years old.
My favorite thing is soccer.
My name is Hanako.
I am 13 years old.
My favorite thing is reading.

Using Return Values

A function can return the result of a calculation. This is called a "return value."

Function to Calculate an Average

def calculate_average(score1, score2, score3):
    total = score1 + score2 + score3
    average = total / 3
    return average  # Return the average

# Try it out
result1 = calculate_average(80, 90, 70)
result2 = calculate_average(100, 85, 95)

print(f"Average of 80, 90, 70: {result1}")
print(f"Average of 100, 85, 95: {result2}")

Result:

Average of 80, 90, 70: 80.0
Average of 100, 85, 95: 93.33333333333333

Function to Judge Attendance Status

Let's make a function that automatically judges attendance status based on the time:

import datetime

def check_attendance(hour, minute):
    # Convert time to minutes for easy comparison
    time_in_minutes = hour * 60 + minute

    # 8:00 is 480 minutes, 10:00 is 600 minutes
    if time_in_minutes < 480:  # Before 8:00
        return "Present"
    elif time_in_minutes <= 600:  # 8:00–10:00
        return "Late"
    else:  # After 10:00
        return "Absent"

# Try it out
result1 = check_attendance(7, 45)  # 7:45
result2 = check_attendance(8, 30)  # 8:30
result3 = check_attendance(10, 15) # 10:15

print(f"7:45: {result1}")
print(f"8:30: {result2}")
print(f"10:15: {result3}")

Result:

7:45: Present
8:30: Late
10:15: Absent

More Practical Attendance Function

You can also make a function that automatically gets the current time and judges attendance:

import datetime

def check_current_attendance():
    now = datetime.datetime.now()
    hour = now.hour
    minute = now.minute

    time_in_minutes = hour * 60 + minute

    if time_in_minutes < 480:  # Before 8:00
        status = "Present"
    elif time_in_minutes <= 600:  # 8:00–10:00
        status = "Late"
    else:  # After 10:00
        status = "Absent"

    return f"{hour}:{minute} - {status}"

# Try it out (the result will change depending on the actual time)
current_status = check_current_attendance()
print(f"Current attendance status: {current_status}")
Prev
§3.0 Advanced