Python Programming for Beginners

Chapter-6: Python Functions – Creating and Using Functions

Chapter 6: Python Functions – Creating and Using Functions

6.1 Introduction

As Python programs become larger, writing all instructions in one place can make the code difficult to understand and maintain.

Functions help solve this problem.

A function is a reusable block of code designed to perform a particular task.

For example, instead of writing the same calculation several times, we can create a function once and call it whenever required.

In this chapter, you will learn:

What functions are

Why functions are useful

How to create a function

How to call a function

Parameters and arguments

Return values

Default arguments

Keyword arguments

Variable-length arguments

Local and global variables

Scope

Docstrings

Lambda functions

Practical projects using functions

6.2 What is a Function?

A function is a named, reusable block of code that performs a specific task.

A simple function looks like this:

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

The keyword def is used to define a function.

However, defining a function does not execute it.

To execute the function, we need to call it:

greet()

Output:

Hello! Welcome to Python.

6.3 Why Use Functions?

Functions provide several benefits.

1. Code Reusability

A function can be called multiple times.

2. Better Organization

Large programs can be divided into smaller tasks.

3. Easier Maintenance

If a calculation needs to be changed, you can update the function instead of changing the same code in many places.

4. Improved Readability

Well-named functions make programs easier to understand.

5. Easier Testing

Individual functions can be tested separately.

6.4 Creating a Function

The basic syntax is:

def function_name():    statements

Example:

def welcome():    print("Welcome to Python Programming")

Here:

def starts the function definition.

welcome is the function name.

() contains parameters, if any.

: marks the beginning of the function body.

The indented code is the function body.

6.5 Calling a Function

After defining a function, you can call it by writing its name followed by parentheses.

def welcome():    print("Welcome to Python") welcome()

Output:

Welcome to Python

A function can be called more than once.

def welcome():    print("Welcome!") welcome() welcome() welcome()

Output:

Welcome! Welcome! Welcome!

6.6 Function with Multiple Statements

A function can contain several statements.

def student_info():    print("Student Information")    print("Name: Aman")    print("Class: 10")    print("Subject: Computer Science") student_info()

All statements inside the function execute when the function is called.

6.7 Function Parameters

A function can receive information through parameters.

Example:

def greet(name):    print("Hello", name) greet("Aman")

Output:

Hello Aman

Here:

name is a parameter.

"Aman" is an argument passed to the function.

6.8 Parameters and Arguments

These two terms are related but have different meanings.

Parameter

A variable written in the function definition.

def greet(name):

Here name is a parameter.

Argument

The actual value supplied when calling the function.

greet("Aman")

Here "Aman" is an argument.

6.9 Function with Multiple Parameters

A function can accept multiple parameters.

def add(a, b):    print(a + b) add(10, 20)

Output:

30

Another example:

def student(name, age, city):    print("Name:", name)    print("Age:", age)    print("City:", city) student("Ravi", 20, "Bhopal")

6.10 Returning a Value

A function can send a result back to the code that called it.

The return statement is used for this purpose.

Example:

def add(a, b):    return a + b result = add(10, 20) print(result)

Output:

30

The function calculates the sum and returns it.

6.11 print() vs return

These two concepts are different.

print()

Displays information on the screen.

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

return

Sends a value back to the caller.

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

A returned value can be stored and used later.

result = add(10, 20) double = result * 2 print(double)

Output:

60

6.12 Returning Multiple Values

Python allows a function to return multiple values.

Example:

def calculate(a, b):    total = a + b    difference = a - b    return total, difference total, difference = calculate(20, 5) print("Total:", total) print("Difference:", difference)

Output:

Total: 25 Difference: 15

Python packages the returned values together so they can be assigned to multiple variables.

6.13 Function Without a return

A function does not have to return a value.

def message():    print("Learning Python is interesting.") message()

If a function reaches the end without returning a value, Python returns None implicitly.

Example:

def test():    print("Hello") result = test() print(result)

Output:

Hello None

6.14 Default Parameters

A parameter can have a default value.

def greet(name="Student"):    print("Hello", name) greet() greet("Aman")

Output:

Hello Student Hello Aman

If an argument is not supplied, the default value is used.

6.15 Multiple Default Parameters

Example:

def student(name="Unknown", age=0):    print("Name:", name)    print("Age:", age) student() student("Ravi", 20)

Default parameters make functions more flexible.

6.16 Keyword Arguments

Arguments can be supplied by parameter name.

Example:

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

Output:

Name: Aman Age: 20

The order of keyword arguments does not have to match the parameter order.

6.17 Positional Arguments

Arguments supplied according to their position are called positional arguments.

def student(name, age):    print(name)    print(age) student("Aman", 20)

Here:

"Aman" is assigned to name.

20 is assigned to age.

6.18 Positional and Keyword Arguments Together

You can combine positional and keyword arguments, but positional arguments must come before keyword arguments.

Example:

def student(name, age, city):    print(name, age, city) student("Aman", age=20, city="Delhi")

This is valid.

6.19 Variable-Length Arguments: *args

Sometimes you may not know how many positional arguments a function will receive.

Python provides *args for this purpose.

Example:

def add_numbers(*numbers):    total = 0    for number in numbers:        total += number    return total print(add_numbers(10, 20)) print(add_numbers(10, 20, 30, 40))

Output:

30 100

Inside the function, numbers behaves like a tuple containing the positional arguments.

6.20 Variable-Length Keyword Arguments: **kwargs

**kwargs allows a function to receive a variable number of keyword arguments.

Example:

def student_info(**details):    for key, value in details.items():        print(key, ":", value) student_info(name="Aman", age=20, city="Delhi")

Output:

name : Aman age : 20 city : Delhi

Inside the function, details behaves like a dictionary.

6.21 Combining Parameters, *args, and **kwargs

Python allows flexible function definitions.

Example:

def example(name, *subjects, **details):    print("Name:", name)    print("Subjects:", subjects)    print("Details:", details) example(    "Aman",    "Maths",    "Science",    age=20,    city="Delhi" )

This technique is useful when designing flexible functions, although beginners should first become comfortable with normal parameters.

6.22 Local Variables

A variable created inside a function is normally local to that function.

Example:

def calculate():    result = 100    print(result) calculate()

The variable result is local to the function.

Trying to use it outside the function normally causes an error because it is not defined in that outer scope.

6.23 Global Variables

A variable defined outside a function is generally in the global scope.

Example:

message = "Welcome" def show_message():    print(message) show_message()

The function can read the global variable.

However, using too many global variables can make programs harder to understand and maintain.

6.24 The global Keyword

Python provides the global keyword when a function needs to reassign a global variable.

Example:

count = 0 def increase():    global count    count += 1 increase() print(count)

Output:

1

For most programs, it is usually better to pass values into functions and return results rather than relying heavily on global state.

6.25 Variable Scope

Scope determines where a variable can be accessed.

Important scopes include:

Local scope

Global scope

Example:

x = 10 def test():    x = 20    print("Inside:", x) test() print("Outside:", x)

Output:

Inside: 20 Outside: 10

The local x inside the function is separate from the global x.

6.26 Function Documentation with Docstrings

A docstring is a string used to document a function.

Example:

def square(number):    """Return the square of a number."""    return number ** 2 print(square(5))

Docstrings help explain what a function does.

They are especially useful in larger projects and reusable code.

6.27 Type Hints

Python allows optional type hints in function definitions.

Example:

def add(a: int, b: int) -> int:    return a + b

Here:

a: int suggests that a is expected to be an integer.

b: int suggests that b is expected to be an integer.

-> int indicates that the function is intended to return an integer.

Type hints improve readability and can help development tools identify potential problems. Python does not automatically enforce these annotations at runtime.

6.28 Lambda Functions

A lambda function is a small anonymous function.

Syntax:

lambda arguments: expression

Example:

square = lambda x: x * x print(square(5))

Output:

25

For simple operations, lambda expressions can be convenient.

For larger or more complex logic, a normal def function is usually clearer.

6.29 Function Calling Another Function

Functions can call other functions.

Example:

def add(a, b):    return a + b def display_sum(a, b):    result = add(a, b)    print("Sum:", result) display_sum(10, 20)

Output:

Sum: 30

This allows larger programs to be divided into smaller reusable components.

6.30 Functions with Conditions

Functions can contain conditional statements.

def check_age(age):    if age >= 18:        return "Eligible"    else:        return "Not eligible" print(check_age(21)) print(check_age(16))

Output:

Eligible Not eligible

6.31 Functions with Loops

Functions can also contain loops.

Example:

def print_numbers(start, end):    for number in range(start, end + 1):        print(number) print_numbers(1, 5)

Output:

1 2 3 4 5

This combines the concepts learned in previous chapters.

6.32 Example: Calculate Area

Create a function to calculate the area of a rectangle.

def rectangle_area(length, width):    return length * width area = rectangle_area(10, 5) print("Area:", area)

Output:

Area: 50

The function can be reused:

print(rectangle_area(5, 4)) print(rectangle_area(12, 6)) print(rectangle_area(20, 10))

6.33 Example: Calculate Average

def average(a, b, c):    return (a + b + c) / 3 result = average(80, 70, 90) print("Average:", result)

Output:

Average: 80.0

6.34 Example: Even or Odd Function

def is_even(number):    return number % 2 == 0 print(is_even(10)) print(is_even(7))

Output:

True False

This function returns a Boolean value.

6.35 Example: Find the Largest Number

def largest(a, b, c):    if a >= b and a >= c:        return a    elif b >= a and b >= c:        return b    else:        return c print(largest(15, 28, 20))

Output:

28

6.36 Example: Student Grade Function

def calculate_grade(marks):    if marks < 0 or marks > 100:        return "Invalid"    elif marks >= 90:        return "A+"    elif marks >= 80:        return "A"    elif marks >= 70:        return "B"    elif marks >= 60:        return "C"    elif marks >= 40:        return "D"    else:        return "F" marks = float(input("Enter marks: ")) print("Grade:", calculate_grade(marks))

This example combines:

Function parameters

return

Conditional statements

Comparison operators

User input

6.37 Example: Simple Calculator Using Functions

Instead of putting every operation in one large block, we can create separate functions.

def add(a, b):    return a + b def subtract(a, b):    return a - b def multiply(a, b):    return a * b def divide(a, b):    if b == 0:        return None    return a / b a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) print("Addition:", add(a, b)) print("Subtraction:", subtract(a, b)) print("Multiplication:", multiply(a, b)) result = divide(a, b) if result is None:    print("Division by zero is not allowed.") else:    print("Division:", result)

This design is easier to organize and extend than putting every operation into one long section of code.

6.38 Function Reusability Example

Suppose a program needs to calculate the area of many rectangles.

Without a function, we might repeatedly write:

area1 = 10 * 5 area2 = 8 * 4 area3 = 15 * 6

Using a function:

def rectangle_area(length, width):    return length * width area1 = rectangle_area(10, 5) area2 = rectangle_area(8, 4) area3 = rectangle_area(15, 6)

The function avoids repeating the calculation logic.

6.39 Recursion Introduction

A function can call itself. This is known as recursion.

Example:

def countdown(number):    if number <= 0:        return    print(number)    countdown(number - 1) countdown(5)

Output:

5 4 3 2 1

A recursive function needs a condition that eventually stops the recursive calls.

Recursion is useful for certain problems, but many tasks can be solved more simply with loops.

6.40 Common Function Mistakes

Mistake 1: Forgetting to call the function

Defining a function does not execute it.

def greet():    print("Hello")

Nothing is displayed until you call it:

greet()

Mistake 2: Incorrect indentation

Incorrect:

def greet(): print("Hello")

Correct:

def greet():    print("Hello")

Mistake 3: Forgetting return

If a function needs to provide a result, make sure it returns the value.

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

Mistake 4: Wrong number of arguments

If a function requires two arguments:

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

Calling:

add(10)

will result in an error because one required argument is missing.

6.41 Mini Project: Student Result System

Functions can make a student result program more organized.

def calculate_total(marks):    return sum(marks) def calculate_average(marks):    return sum(marks) / len(marks) def calculate_grade(average):    if average >= 90:        return "A+"    elif average >= 80:        return "A"    elif average >= 70:        return "B"    elif average >= 60:        return "C"    elif average >= 40:        return "D"    else:        return "F" name = input("Enter student name: ") marks = [] for i in range(3):    mark = float(input(f"Enter marks for subject {i + 1}: "))    marks.append(mark) total = calculate_total(marks) average = calculate_average(marks) grade = calculate_grade(average) print("\nStudent:", name) print("Total:", total) print("Average:", average) print("Grade:", grade)

This program demonstrates how functions can divide a larger task into smaller parts.

6.42 Mini Project: Temperature Converter

def celsius_to_fahrenheit(celsius):    return (celsius * 9 / 5) + 32 def fahrenheit_to_celsius(fahrenheit):    return (fahrenheit - 32) * 5 / 9 choice = input("Enter C to convert Celsius or F to convert Fahrenheit: ").upper() if choice == "C":    temperature = float(input("Enter Celsius: "))    result = celsius_to_fahrenheit(temperature)    print("Fahrenheit:", result) elif choice == "F":    temperature = float(input("Enter Fahrenheit: "))    result = fahrenheit_to_celsius(temperature)    print("Celsius:", result) else:    print("Invalid choice.")

6.43 Mini Project: Simple Calculator

def add(a, b):    return a + b def subtract(a, b):    return a - b def multiply(a, b):    return a * b def divide(a, b):    if b == 0:        return None    return a / b while True:    print("\n--- Calculator ---")    print("1. Addition")    print("2. Subtraction")    print("3. Multiplication")    print("4. Division")    print("5. Exit")    choice = input("Enter choice: ")    if choice == "5":        print("Calculator closed.")        break    if choice in ("1", "2", "3", "4"):        first = float(input("Enter first number: "))        second = float(input("Enter second number: "))        if choice == "1":            print("Result:", add(first, second))        elif choice == "2":            print("Result:", subtract(first, second))        elif choice == "3":            print("Result:", multiply(first, second))        elif choice == "4":            result = divide(first, second)            if result is None:                print("Cannot divide by zero.")            else:                print("Result:", result)    else:        print("Invalid choice.")

This project demonstrates how functions can be used inside loops and conditional statements.

6.44 Chapter Summary

In this chapter, you learned:

What functions are

Why functions are useful

How to define functions using def

How to call functions

Parameters and arguments

Positional arguments

Keyword arguments

Default parameters

return

Returning multiple values

*args

**kwargs

Local and global variables

Variable scope

Docstrings

Type hints

Lambda functions

Functions with conditions

Functions with loops

Function reuse

Basic recursion

Practical function-based programs

Functions are one of the most important concepts in Python because they help developers create programs that are organized, reusable, and easier to maintain.

Quick Revision Questions

1. What is a function?
A function is a reusable block of code designed to perform a particular task.

2. Which keyword is used to define a function?
def

3. How do you call a function named greet?

greet()

4. What is a parameter?
A parameter is a variable specified in a function definition.

5. What is an argument?
An argument is a value supplied when calling a function.

6. Which keyword sends a result back from a function?
return

7. What is a default parameter?
A parameter that has a predefined value used when no corresponding argument is supplied.

8. What is *args used for?
It allows a function to receive a variable number of positional arguments.

9. What is **kwargs used for?
It allows a function to receive a variable number of keyword arguments.

10. What is a local variable?
A variable defined inside a function whose normal scope is limited to that function.

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

12. What is a lambda function?
A small anonymous function generally used for simple expressions.

Practice Exercises

Exercise 1: Greeting Function

Create a function that accepts a person's name and displays a personalized greeting.

Exercise 2: Addition Function

Create a function that accepts two numbers and returns their sum.

Exercise 3: Even or Odd

Create a function that accepts a number and returns whether it is even or odd.

Exercise 4: Maximum Number

Create a function that accepts three numbers and returns the largest one.

Exercise 5: Factorial Function

Create a function that accepts a positive integer and returns its factorial.

Exercise 6: Temperature Conversion

Create two functions:

Celsius to Fahrenheit

Fahrenheit to Celsius

Exercise 7: Student Grade

Create a function that accepts marks and returns a grade.

Exercise 8: Calculator

Create separate functions for:

Addition

Subtraction

Multiplication

Division

Then build a calculator using those functions.

Exercise 9: *args

Create a function that accepts any number of numbers and returns their total.

Exercise 10: Student Information

Create a function that accepts student name, age, class, and city and displays the information.

Chapter Activity

Create a Student Management Program using Functions.

Your program should contain separate functions for:

Adding student information.

Calculating total marks.

Calculating average marks.

Calculating grade.

Displaying the final result.

Use a loop to allow information for multiple students to be entered.

Try to keep each function focused on one specific task.

Next Chapter: Python Lists – Creating, Accessing and Modifying Lists