Understanding Python Functions: Arguments, Return Values, and Default Arguments

Introduction

Functions are a fundamental aspect of Python programming that allow you to encapsulate reusable code. Understanding how to define functions, pass arguments, use return values, and set default arguments is crucial for writing efficient Python code. This tutorial will cover how to define functions with arguments, return values, and the concept of default arguments in Python.

Objective

The objective of this tutorial is to help you understand the following concepts:

  • How to define and call functions in Python.
  • How to pass different types of arguments to functions.
  • How to use return values in functions.
  • How to set default values for function arguments.

Code Example


# Python Function with Arguments, Return Values, and Default Arguments

# Function definition with arguments
def greet(name, age=25):
    """Greets the person by their name and age"""
    return f"Hello {name}, you are {age} years old!"

# Function calling with an argument
message1 = greet("Alice")
print(message1)

# Function calling with both arguments
message2 = greet("Bob", 30)
print(message2)

Explanation of the Program Structure

In this example:

  • The function greet(name, age=25) is defined with two parameters: name and age. The age parameter has a default value of 25.
  • When we call the function with just one argument, greet("Alice"), the default value of age (25) is used.
  • When we call the function with both arguments, greet("Bob", 30), the value 30 is used for the age parameter.
  • The function returns a greeting message which is then printed to the console.

How to Run the Program

To run this Python program, follow these steps:

  1. Open a text editor and copy the code provided above into a new Python file (e.g., greet.py).
  2. Save the file with the .py extension.
  3. Open a terminal or command prompt and navigate to the folder where the Python file is saved.
  4. Run the Python file by typing python greet.py and pressing Enter.
  5. You should see the output of the greetings printed in the terminal or command prompt.
© 2025 Learn Programming. All rights reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *