Paramclasses Academy - Blog

Tutorials Details

←
Post 11 of 20
→

Python Functions: Parameters, Return Values, Scope & Lambda

Python Functions: Parameters, Return Values, Scope & Lambda

October 17, 2026

Python Functions: Parameters, Return Values, Scope & Lambda

Introduction to Python Functions

A function in Python is a reusable block of code designed to perform a specific task. Instead of writing the same code multiple times, we can create a function and call it whenever required.

Functions make programs easier to read, maintain, test, and reuse. They are an essential concept in Python programming and are widely used in real-world applications.

For example, an application may need to calculate totals, validate user input, display messages, or calculate student marks. These tasks can be organized into separate functions.

1. What Is a Function in Python?

A function is a named block of code that executes when it is called.

Syntax

def function_name():
    # Code to execute
    pass
  • def is the keyword used to define a function.

  • function_name is the name of the function.

  • Parentheses () can contain parameters.

  • The colon : begins the function body.

  • Indentation defines the statements inside the function.

Example

def greet():
    print("Welcome to Python!")

greet()

Output:

Welcome to Python!

The function is defined using def and executed by calling greet().

2. Why Do We Use Functions?

Functions provide several advantages:

  1. Code Reusability: Write code once and use it multiple times.

  2. Modularity: Divide a large program into smaller tasks.

  3. Readability: Make code easier to understand.

  4. Maintainability: Update one function instead of changing repeated code.

  5. Testing: Test individual tasks more easily.

  6. Reduced Duplication: Avoid writing the same logic repeatedly.

Example: Without a Function

print("Welcome, Rahul!")
print("Welcome, Priya!")
print("Welcome, Amit!")

Example: With a Function

def welcome(name):
    print(f"Welcome, {name}!")

welcome("Rahul")
welcome("Priya")
welcome("Amit")

Output:

Welcome, Rahul!
Welcome, Priya!
Welcome, Amit!

The second approach is more reusable and easier to maintain.

3. Types of Functions in Python

Python functions are commonly discussed in two main categories.

Built-in Functions

Built-in functions are already provided by Python.

Examples include:

print("Hello")
print(len("Python"))
print(max(10, 20, 30))
print(min(10, 20, 30))
print(sum([10, 20, 30]))
print(type(100))

Output:

Hello
6
30
10
60

User-Defined Functions

User-defined functions are created by programmers using the def keyword.

def calculate_square(number):
    return number * number

print(calculate_square(5))

Output:

25

Python also supports anonymous functions created with lambda, which are covered later in this tutorial.

4. Function Parameters and Arguments

Parameters and arguments are related, but they have different meanings.

  • Parameter: A variable listed in the function definition.

  • Argument: An actual value passed to the function when it is called.

Example

def greet(name):
    print(f"Hello, {name}!")

greet("Rahul")

Here, name is the parameter, while "Rahul" is the argument.

Output:

Hello, Rahul!

5. Types of Function Arguments

Python supports several ways to pass arguments to functions.

A. Positional Arguments

Values are assigned to parameters according to their position.

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

student("Rahul", 21)

Output:

Name: Rahul
Age: 21

The first argument is assigned to name, and the second is assigned to age.

B. Keyword Arguments

Keyword arguments specify parameter names when calling a function.

def student(name, age):
    print(name, age)

student(age=21, name="Rahul")

Output:

Rahul 21

Keyword arguments allow you to provide values in a different order.

C. Default Arguments

A default parameter value is used when the caller does not provide that argument.

def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()
greet("Priya")

Output:

Hello, Guest!
Hello, Priya!

D. Variable-Length Positional Arguments: *args

Use *args when a function needs to accept a variable number of positional arguments.

def calculate_total(*numbers):
    print(sum(numbers))

calculate_total(10, 20)
calculate_total(10, 20, 30, 40)

Output:

30
100

Inside the function, numbers is a tuple.

E. Variable-Length Keyword Arguments: **kwargs

Use **kwargs when a function needs to accept a variable number of keyword arguments.

def show_details(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

show_details(name="Rahul", age=21, city="Raipur")

Output:

name: Rahul
age: 21
city: Raipur

Inside the function, details is a dictionary.

6. The Return Statement in Python

The return statement sends a result back to the code that called the function.

A function can return a value, which can then be stored in a variable, displayed, or used in another calculation.

Example

def add(a, b):
    return a + b

result = add(10, 20)
print(result)

Output:

30

The function calculates the sum and returns the result.

Difference Between print() and return

  • print() displays information on the screen.

  • return sends a value back to the caller.

  • A returned value can be reused in further calculations.

def multiply(a, b):
    return a * b

answer = multiply(5, 4)
print(answer + 10)

Output:

30

The returned value 20 is stored in answer, and then 10 is added to it.

Returning Multiple Values

Python allows a function to return multiple values. They are returned together as a tuple.

def calculate(a, b):
    return a + b, a - b, a * b

addition, subtraction, multiplication = calculate(10, 5)

print(addition)
print(subtraction)
print(multiplication)

Output:

15
5
50

What Happens When a Function Has No Return Statement?

If a function finishes without executing a return statement, it returns None.

def display_message():
    print("Learning Python Functions")

result = display_message()
print(result)

Output:

Learning Python Functions
None

7. Local and Global Variables

Variable scope determines where a variable can be accessed.

Local Variables

A local variable is created inside a function and is normally accessible only within that function.

def show_number():
    number = 100
    print(number)

show_number()

Output:

100

Trying to access number outside the function will raise a NameError because the variable is local to the function.

Global Variables

A global variable is defined outside functions and can generally be read inside them.

message = "Welcome to Python"

def show_message():
    print(message)

show_message()
print(message)

Output:

Welcome to Python
Welcome to Python

Using the global Keyword

Use global when a function needs to reassign a variable defined in the global scope.

count = 0

def increase_count():
    global count
    count += 1

increase_count()
print(count)

Output:

1

Although global is useful in certain situations, passing values through parameters and returning results often makes programs easier to test and maintain.

The nonlocal Keyword

The nonlocal keyword allows a nested function to reassign a variable from its nearest enclosing function scope, excluding the global scope.

def outer():
    message = "Hello"

    def inner():
        nonlocal message
        message = "Hello, Python!"

    inner()
    print(message)

outer()

Output:

Hello, Python!

8. Lambda Functions in Python

A lambda function is a small anonymous function defined with the lambda keyword. It can contain only a single expression.

Syntax

lambda arguments: expression

Example

square = lambda number: number * number

print(square(5))

Output:

25

This lambda function takes one argument and returns its square.

Lambda With Multiple Arguments

add = lambda a, b: a + b

print(add(10, 20))

Output:

30

Using Lambda With sorted()

Lambda functions are useful for providing a custom sorting key.

students = [
    ("Rahul", 75),
    ("Priya", 92),
    ("Amit", 81)
]

students.sort(key=lambda student: student[1])

print(students)

Output:

[('Rahul', 75), ('Amit', 81), ('Priya', 92)]

The list is sorted by marks in ascending order.

Lambda With map()

The map() function applies a function to every item in an iterable.

numbers = [1, 2, 3, 4, 5]

squares = list(map(lambda number: number ** 2, numbers))

print(squares)

Output:

[1, 4, 9, 16, 25]

Lambda With filter()

The filter() function selects items that satisfy a condition.

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = list(filter(lambda number: number % 2 == 0, numbers))

print(even_numbers)

Output:

[2, 4, 6]

For more complex logic, a regular function defined with def is usually easier to read.

9. Recursive Functions in Python

A recursive function calls itself to solve a smaller version of the same problem.

Every recursive function should have a base case that stops the recursion.

Example: Factorial

The factorial of a positive integer is the product of all positive integers up to that number. By convention, 0! is 1.

def factorial(number):
    if number < 0:
        raise ValueError("Number must not be negative")

    if number == 0:
        return 1

    return number * factorial(number - 1)

print(factorial(5))

Output:

120

The calculation is:

5 × 4 × 3 × 2 × 1 = 120

Recursive functions are useful for certain problems, but deep recursion can exceed Python's recursion limit. Iteration may be more suitable for some tasks.

10. Docstrings in Python Functions

A docstring is a string written at the beginning of a function to explain what it does.

def calculate_square(number):
    """Return the square of a number."""
    return number * number

print(calculate_square(4))
print(calculate_square.__doc__)

Output:

16
Return the square of a number.

Docstrings improve code documentation and help other developers understand the purpose of a function.

11. Practical Project: Student Marks Calculator

Let's create a simple student marks calculator using functions.

def calculate_total(marks):
    return sum(marks)

def calculate_percentage(marks):
    if not marks:
        return 0

    return calculate_total(marks) / len(marks)

def display_result(name, marks):
    total = calculate_total(marks)
    percentage = calculate_percentage(marks)

    print("Student Name:", name)
    print("Total Marks:", total)
    print("Percentage:", f"{percentage:.2f}%")

    if percentage >= 80:
        print("Grade: A")
    elif percentage >= 60:
        print("Grade: B")
    elif percentage >= 40:
        print("Grade: C")
    else:
        print("Grade: Needs Improvement")

student_name = "Rahul"
student_marks = [85, 90, 78, 88, 92]

display_result(student_name, student_marks)

Output:

Student Name: Rahul
Total Marks: 433
Percentage: 86.60%
Grade: A

This project demonstrates how multiple functions can work together to organize a program into smaller, reusable tasks.

Note: This example assumes that every subject has a maximum of 100 marks and all subjects have equal weight.

12. Best Practices for Writing Python Functions

Follow these practices when writing professional Python code:

  1. Use meaningful function names, such as calculate_total() or validate_email().

  2. Follow Python's naming convention by using snake_case.

  3. Keep each function focused on one main responsibility.

  4. Use parameters instead of relying unnecessarily on global variables.

  5. Return results when the calling code needs to reuse them.

  6. Add docstrings to explain complex or important functions.

  7. Avoid unnecessarily long functions.

  8. Validate input when required.

  9. Avoid mutable default arguments such as items=[]; use None when appropriate.

  10. Prefer readable code over clever but confusing expressions.

Example: Avoid Mutable Default Arguments

Incorrect approach:

def add_item(item, items=[]):
    items.append(item)
    return items

The same list can be reused across calls because the default list is created once.

Better approach:

def add_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items

print(add_item("Book"))
print(add_item("Pen"))

Output:

['Book']
['Pen']

Each call creates a new list when no list is supplied.

13. Common Mistakes in Python Functions

Mistake 1: Forgetting to Call the Function

def greet():
    print("Hello")

Defining a function does not execute it. Call it using greet().

Mistake 2: Incorrect Indentation

Python uses indentation to identify the function body.

def greet():
    print("Hello")

Mistake 3: Missing Required Arguments

def add(a, b):
    return a + b

# add(10)  # Raises TypeError because b is missing
print(add(10, 20))

Mistake 4: Confusing print() With return

If another part of your program needs the calculated value, return it instead of only printing it.

Mistake 5: Using a Local Variable Outside Its Scope

A local variable generally cannot be accessed outside the function in which it is defined.

Mistake 6: Forgetting the Base Case in Recursion

A recursive function without a suitable stopping condition can continue until Python raises a recursion-related error.

14. Python Functions Practice Programs

Practice the following programs to strengthen your understanding:

  1. Create a function that adds two numbers.

  2. Create a function that checks whether a number is even or odd.

  3. Write a function that returns the largest of three numbers.

  4. Create a function to calculate the factorial of a number.

  5. Write a function to check whether a number is prime.

  6. Create a function that calculates the area of a rectangle.

  7. Write a function that counts vowels in a string.

  8. Create a function that returns the maximum and minimum values in a list.

  9. Write a lambda function that calculates the cube of a number.

  10. Create a student result calculator using separate functions.

15. Python Functions Interview Questions

Q1. What is a function in Python?

A function is a reusable block of code that performs a particular task.

Q2. Which keyword is used to define a function?

The def keyword.

Q3. What is the difference between a parameter and an argument?

A parameter appears in the function definition, while an argument is a value supplied when calling the function.

Q4. What is the purpose of the return statement?

It sends a value back to the caller and ends the current function execution.

Q5. What does a function return if it has no explicit return statement?

It returns None when execution reaches the end without returning another value.

Q6. What are default arguments?

They are parameter values used when the caller does not supply the corresponding argument.

Q7. What are *args and **kwargs?

*args collects extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary.

Q8. What is a lambda function?

A lambda function is an anonymous function consisting of a single expression.

Q9. What is recursion?

Recursion occurs when a function calls itself to solve a smaller version of a problem.

Q10. What is variable scope?

Variable scope determines where a variable can be accessed in a program.

Q11. What is the difference between local and global variables?

Local variables belong to a local function scope, while global variables are defined at the module level.

Q12. What is a docstring?

A docstring is a string used to document a function, class, or module.

Conclusion

Python functions are fundamental to writing organized, reusable, and maintainable programs. By understanding function definitions, parameters, arguments, return values, variable scope, lambda functions, recursion, and docstrings, you can build more structured Python applications.

Practice these concepts with small programs before moving on to modules, packages, file handling, and object-oriented programming.

←
Post 11 of 20
→