Understanding Function Arguments and Return Values in Python

 



Understanding Function Arguments and Return Values in Python


Introduction

In Python, functions are the building blocks of organized and reusable code.
But to make them powerful, we use arguments and return values to pass and receive information.

Let’s understand how they work with clear examples 

1. Types of Function Arguments

Python allows different ways of passing data to functions.

Type Description
Positional Arguments Values passed in the same order as parameters
Keyword Arguments Values assigned by name
Default Arguments Parameters that have a default value
Variable-Length Arguments Used when you don’t know how many values will be passed

2. Positional Arguments

The position of arguments matters!

def student_info(name, age):
    print("Name:", name)
    print("Age:", age)

student_info("Ravi", 20)

Output:

Name: Ravi
Age: 20

If you change the order:

student_info(20, "Ravi")

The output changes too — Python doesn’t know which is which!


3. Keyword Arguments

You can specify argument names to avoid confusion.

student_info(age=20, name="Ravi")

Output:

Name: Ravi
Age: 20

4. Default Arguments

You can assign default values to parameters.

def greet(name, message="Welcome to Python!"):
    print(name + ", " + message)

greet("Asha")
greet("Ravi", "Good Morning!")

Output:

Asha, Welcome to Python!
Ravi, Good Morning!

5. Variable-Length Arguments

Sometimes, you may not know how many arguments you’ll receive.

 *Using args (Non-Keyword Arguments)

def add(*numbers):
    total = sum(numbers)
    print("Total =", total)

add(10, 20, 30)
add(5, 15)

Output:

Total = 60
Total = 20

 **Using kwargs (Keyword Arguments)

def display_details(**info):
    for key, value in info.items():
        print(key, ":", value)

display_details(name="Ravi", age=20, course="Python")

Output:

name : Ravi
age : 20
course : Python

6. Return Values

A function can return one or more values using the return keyword.

def calculate(a, b):
    sum = a + b
    diff = a - b
    return sum, diff

result = calculate(10, 5)
print(result)

Output:

(15, 5)

Challenge for You

Write a Python function average_marks(*marks) that calculates and returns the average of given marks.
Then print the result for 5 subjects.


Conclusion

Understanding arguments and return values helps you design flexible, reusable functions.
Mastering them gives you real control over your program’s flow and data.



Comments