🇯🇵 日本語 | 🇺🇸 English | 🇪🇸 Español | 🇵🇹 Português | 🇹🇭 ไทย | 🇨🇳 中文

【Copy-Paste to Run】Mastering Python Functions: From `def` Basics to Advanced Usage

To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you haven’t installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.

When you're building websites or developing apps, do you ever find yourself thinking, "Wait, I just wrote this same piece of code..."? It's a common experience. The solution to this repetitive work is what we're introducing today: Python "functions".

In this article, we'll explain everything from the basic way to create Python functions to some handy advanced techniques, all with plenty of sample code so that even programming beginners can follow along with confidence. The key phrase is "copy-paste to run." Let's put the difficult theory aside for now and first experience the joy of seeing your own code work!


First of All, What is a Python "Function"?

The easiest way to imagine a function might be a "vending machine".

In this way, a function is a "bundle of specific tasks (processes)". Once you create one, you can call it over and over again to perform the same job, just like pressing a button. This has the major advantage of making your code shorter, simpler, and easier to modify.

In Python, you create these functions using a statement called def (the def statement). Let's dive right in and see how to create them!


【The Basics】How to Create and Use Python Functions

Let's start with the absolute basics. We'll create the simplest possible function, one with no arguments and no return value.

1. Basic Syntax: Defining a Function with `def`

To create a function, you start by writing def function_name():, and then, starting on the next line, you indent to write the processing content. Here, we'll create a simple function called say_hello that just displays "Hello!".

# 1. Define the function
def say_hello():
  print("Hello!")

# 2. Call the function
say_hello()

Execution Result:

Hello!

The key point is that nothing happens just by defining (creating) the function. It's only when you write the function name followed by parentheses, like say_hello(), that the function is called and the code inside it is executed.


2. Let's Try Using Arguments

Next, let's try using "arguments," which are the "money" in our vending machine analogy. By using arguments, you can pass information from outside the function and change what it does.

Here, we'll create a function called greet that returns a greeting for a given name. When you put a variable name (in this case, name) inside the parentheses, like def greet(name):, it becomes an argument.

# Define a function that accepts an argument
def greet(name):
  print(f"Hello, {name}!")

# Pass specific values as arguments when calling the function
greet("Tanaka")
greet("Suzuki")

Execution Result:

Hello, Tanaka!
Hello, Suzuki!

As you can see, just by changing the value passed as an argument, we were able to flexibly change the result of the same function.


3. Get Results with a Return Value

Now for the "drink" from the vending machine: the "return value". You use this when you want to send a result calculated inside the function back to where the function was called. To return a value, you use the return statement.

Let's create an add function that takes two numbers and returns their sum.

# A function that takes two arguments and returns their sum
def add(a, b):
  total = a + b
  return total # Use the return statement to send back the result

# Call the function and store the return value in the variable 'result'
result = add(5, 3)

print(f"The result of 5 + 3 is {result}.")

Execution Result:

The result of 5 + 3 is 8.

When add(5, 3) is executed, total = 8 is calculated inside the function, and the value 8 is returned by the return statement to where the function was called. Then, the returned 8 is assigned to the variable result.

By using return instead of just printing directly with print(), you can use the result of the calculation in another process, which is extremely useful.


【Advanced】More Convenient Ways to Use Functions

Now that you've got the basics down, let's look at some more advanced ways to use functions. Mastering these will enable you to write more flexible and efficient code.

1. Default Arguments: No Argument? No Problem!

Sometimes you want to be able to omit an argument when calling a function. That's where "default arguments" come in handy. You set a default value in advance, like this: def function_name(argument_name="default_value"):.

# Set a default value "en" for the second argument, lang
def greet_language(name, lang="en"):
  if lang == "ja":
    message = f"{name}さん、こんにちは!" # Hello, {name}! in Japanese
  elif lang == "en":
    message = f"Hello, {name}!"
  else:
    message = "Language not specified."
  
  return message

# Omit the second argument (the default value "en" will be used)
print(greet_language("Sato"))

# Specify the second argument
print(greet_language("John", lang="en"))

Execution Result:

Hello, Sato!
Hello, John!

If you omit the argument as in `greet_language("Sato")`, it is automatically treated as `lang="en"`, so an English greeting is output. Very convenient!


2. Keyword Arguments: Don't Worry About Argument Order

When a function has many arguments, it can be hard to remember their order. If you use "keyword arguments," you can specify them in the format `argument_name=value`, so you don't need to worry about the order.

def create_user_profile(name, age, country):
  return f"Name: {name}, Age: {age}, Country: {country}"

# Specify arguments in order
profile1 = create_user_profile("Yamada", 30, "Japan")
print(profile1)

# Use keyword arguments to specify in a different order
profile2 = create_user_profile(country="USA", name="Emily", age=25)
print(profile2)

Execution Result:

Name: Yamada, Age: 30, Country: Japan
Name: Emily, Age: 25, Country: USA

Using keyword arguments also has the benefit of making your code more readable, as it's immediately clear which value is being passed to which argument.


【Hands-on Corner】Run a Python Function in Your Browser

Finally, let's try running Python using just an HTML file, something web creators are already familiar with! Copy the entire code block below, save it with a name like `index.html`, and open it in your browser. You'll have a simple web application that returns a greeting based on the text you enter.

This uses a technology called PyScript to run Python code directly inside an HTML file. No complicated setup is required. Please experience the "copy-paste to run" for yourself!

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Experience Python Functions in the Browser!</title>
  <!-- Loading PyScript -->
  <link rel="stylesheet" href="https://pyscript.net/releases/2024.1.1/core.css">
  <script type="module" src="https://pyscript.net/releases/2024.1.1/core.js"></script>
  <style>
    body { font-family: sans-serif; padding: 2em; line-height: 1.6; }
    input { padding: 8px; font-size: 1em; }
    button { padding: 8px 16px; font-size: 1em; cursor: pointer; }
    #output { margin-top: 1em; font-weight: bold; font-size: 1.2em; color: #2c3e50; }
  </style>
</head>
<body>

  <h1>Greeting Generator</h1>
  <p>Enter your name and press the button.</p>

  <input id="user-name" type="text" placeholder="Enter name...">
  <button py-click="generate_greeting">Generate Greeting</button>
  
  <div id="output"></div>

  <py-script>
    from pyscript import document

    # ★Define the Python function here★
    def create_greeting_message(name):
      # If the name is empty, return a default greeting
      if not name:
        return "Please enter your name!"
      # If there is a name, return a greeting using that name
      return f"Welcome to the web world, {name}!"

    # Function to be executed when the button is clicked
    def generate_greeting(event):
      # Get user input from the input element
      input_element = document.querySelector("#user-name")
      user_name = input_element.value
      
      # Create a greeting message using the function defined above
      message = create_greeting_message(user_name)
      
      # Write the message to the div element for display
      output_div = document.querySelector("#output")
      output_div.innerText = message
  </py-script>

</body>
</html>

Points to Be Careful About When Using Functions

Functions are very powerful, but there are a few points to be careful about to use them correctly.

  1. Indentation is life!
    In Python, indentation signifies a block of code. The processing after def must always be indented with the same number of spaces (usually four). If the indentation is off, it will cause an error.
  2. Use clear function names
    A function's name should make it immediately clear what the function does. For example, names that include a verb, like add or create_user_profile, are common. Bad examples are names like function1 or proc that don't reveal their purpose.
  3. Be aware of variable scope
    A variable defined inside a function (a local variable) cannot be used outside of that function. This is an important mechanism to prevent functions from unintentionally affecting the outside world.

Let's look at an example of variable scope.

def my_function():
  # local_variable is a local variable valid only inside my_function
  local_variable = "This is a variable inside the function"
  print(local_variable)

# Execute the function
my_function()

# Trying to access local_variable from outside the function causes an error
# print(local_variable) # NameError: name 'local_variable' is not defined

Execution Result:

This is a variable inside the function

If you uncomment the last line, print(local_variable), and run it, a NameError will occur. This is because local_variable does not exist outside the function. This property of having a "limited scope of influence" is what makes code safe and easy to manage.


Conclusion: Master Functions and Take Your Programming to the Next Level!

In this article, we've learned everything from the basics to the applications of Python functions, along with lots of code you can copy and paste to run.

Functions are one of the most basic and most important concepts in programming. They eliminate the need to write the same process over and over, and they dramatically improve the overall readability of your code.

First, try playing around with the sample code in this article and creating your own functions. Experiencing "it works" is the fastest way to improve.

Once you've mastered functions, why not learn how to handle data collectively? The following article provides a detailed explanation of "lists" and "dictionaries," the most commonly used data structures in Python.

Next Step: Learn About Python Data Structures like Lists and Dictionaries