Python

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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)