Today, I reviewed the basics of functions in Python.
Function is simply “a named block of code that performs a specific task.”
Once defined, a function can be reused as many times as you want—this makes your code cleaner and more efficient.
In Python, you define a function using the keyword def.
Here are some examples I practiced today.
1. Function to Return the Average of Two Numbers
def average(a, b):
result = (a + b) / 2
return result
ave = average(3, 8)
print(f"The average is {ave}.\n")
2. Function to Determine Whether a Number Is Even or Odd
def check_even(num):
if num % 2 == 0:
return "偶数です"
else:
return "奇数です"
che = check_even(9)
print(f"The result is {che}.\n")
3. Function to Return the Sum of a List
def sum_list(nums):
result = 0
for n in nums:
result += n
return result
result = sum_list([3, 5, 8, 2])
print(f"The total is {result}.\n")
In the final problem, I combined function definitions with for loops and list operations.
This allowed me to perform data filtering—selecting only the necessary data from a larger set. This concept is deeply connected to real-world web applications: for example, displaying only unread emails in a mail app or showing only in-stock items on an e-commerce site.
When I can relate what I learn in Python to everyday tools and services, my understanding deepens and my motivation grows.
Top comments (0)