Functions in Python

What is a Function?

The Problem Without Functions

Look at this program:


    # Calculating area of rectangle 1
    length1 = 10
    width1 = 5
    area1 = length1 * width1
    print(f"Area of rectangle 1: {area1}")

    # Calculating area of rectangle 2
    length2 = 8
    width2 = 3
    area2 = length2 * width2
    print(f"Area of rectangle 2: {area2}")

    # Calculating area of rectangle 3
    length3 = 15
    width3 = 7
    area3 = length3 * width3
    print(f"Area of rectangle 3: {area3}")

You're writing the same logic 3 times. Now imagine doing this for 100 rectangles. Nightmare.

Functions solve this problem.


What is a Function?

A function is a reusable block of code that you write once and use as many times as you want.

Real life analogy: Think of a function like a mixer/blender. You built it once. Now whenever you want to blend something — you just put ingredients in and press the button. You don't rebuild the blender every time.


Basic Syntax


    def function_name():
        # code inside function

  • def keyword tells Python "I'm defining a function"
  • function_name is what you name it
  • : colon at the end — just like if/for/while
  • Code inside must be indented

Your First Function


    def say_hello():
        print("Hello!")
        print("Welcome to Python")

    # Calling the function
    say_hello()

Output:
Hello!
Welcome to Python

Defining a function doesn't run it. You have to call it by writing its name with ().


Call it Multiple Times


    def say_hello():
        print("Hello!")
        print("Welcome to Python")

    say_hello()    # first call
    say_hello()    # second call
    say_hello()    # third call

Output:

Hello!
Welcome to Python
Hello!
Welcome to Python
Hello!
Welcome to Python

Write once, use many times. That's the power.


Parameters — Giving Input to Functions

Right now our function does the same thing every time. What if we want it to greet different people?

We use parameters — variables that receive values when the function is called:


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

    greet("Gagan")
    greet("Rahul")
    greet("Priya")

Output:

Hello, Gagan!
Welcome to Python, Gagan!
Hello, Rahul!
Welcome to Python, Rahul!
Hello, Priya!
Welcome to Python, Priya!

Here name is a parameter — it acts like a variable inside the function that receives whatever value you pass when calling.


Multiple Parameters


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

    greet("Gagan", "Delhi")
    greet("Rahul", "Mumbai")

Output:

Hello Gagan, from Delhi!
Hello Rahul, from Mumbai!

Order matters — first value goes to first parameter, second to second.


Now Fix the Rectangle Problem


    def calculate_area(length, width):
        area = length * width
        print(f"Area = {area}")

    calculate_area(10, 5)
    calculate_area(8, 3)
    calculate_area(15, 7)

Output:

Area = 50
Area = 24
Area = 105

Same logic written once, used 3 times. Clean and simple.


Return — Getting Output from a Function

So far our functions just print things. But what if you want to use the result of a function somewhere else in your code?

Use the return keyword:


    def calculate_area(length, width):
        area = length * width
        return area          # send this value back to whoever called the function

Now you can store the returned value:


    def calculate_area(length, width):
        area = length * width
        return area

    result = calculate_area(10, 5)
    print(f"The area is {result}")

    # Or use it directly in math
    total_area = calculate_area(10, 5) + calculate_area(8, 3)
    print(f"Total area = {total_area}")

Output:

The area is 50
Total area = 74

print vs return — Important Difference

This confuses many beginners. Let's clear it up:


    # Function with print — just displays, can't reuse the value
    def add_with_print(a, b):
        print(a + b)

    # Function with return — sends value back, you can use it
    def add_with_return(a, b):
        return a + b
    result1 = add_with_print(3, 4)    # prints 7, but result1 is None
    result2 = add_with_return(3, 4)   # result2 is 7, you can use it

    print(result1)          # None
    print(result2)          # 7
    print(result2 * 2)      # 14 — you can do math with it

Rule of thumb:

  • Use print inside a function only for debugging or when displaying is the only purpose
  • Use return when you need to use the result somewhere else — which is most of the time

Default Parameters

You can give parameters a default value — used when caller doesn't provide one:


    def greet(name, message="Good morning"):
        print(f"{message}, {name}!")

    greet("Gagan")                        # uses default message
    greet("Rahul", "Good evening")        # overrides default
    greet("Priya", "Happy birthday")      # overrides default

Output:
Good morning, Gagan!
Good evening, Rahul!
Happy birthday, Priya!

Parameters with defaults must always come after parameters without defaults:

def greet(message="Hello", name):   # WRONG
def greet(name, message="Hello"):   # CORRECT

Returning Multiple Values

Python functions can return more than one value:


    def min_max(a, b, c):
        minimum = min(a, b, c)
        maximum = max(a, b, c)
        return minimum, maximum

    small, large = min_max(5, 2, 8)
    print(f"Min: {small}, Max: {large}")

Output:

Min: 2, Max: 8

min() and max() are Python built-in functions that find smallest and largest values.


Scope — Where Variables Live

This is important to understand:

Local variable — created inside a function, only exists inside that function:


    def my_function():
        x = 10          # local variable — only exists inside this function
        print(x)

    my_function()
    print(x)            # ERROR! x doesn't exist outside the function

Global variable — created outside all functions, accessible everywhere:


    name = "Gagan"      # global variable

    def my_function():
        print(name)     # can access global variable inside function

    my_function()       # Gagan
    print(name)         # Gagan — works outside too

Think of it like this — what happens in a function, stays in a function. Local variables are created when the function runs and destroyed when it finishes.


Real World Example — Calculator with Functions

Let's rebuild the calculator properly using 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 "Error: Cannot divide by zero"
        return a / b

    def show_menu():
        print("\n=== Calculator ===")
        print("1. Add")
        print("2. Subtract")
        print("3. Multiply")
        print("4. Divide")
        print("5. Exit")

    while True:
        show_menu()
        choice = input("Enter choice: ")

        if choice == "5":
            print("Goodbye!")
            break

        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == "1":
            print(f"Result: {add(num1, num2)}")
        elif choice == "2":
            print(f"Result: {subtract(num1, num2)}")
        elif choice == "3":
            print(f"Result: {multiply(num1, num2)}")
        elif choice == "4":
            print(f"Result: {divide(num1, num2)}")
        else:
            print("Invalid choice")

Notice how clean this is — each operation has its own function. If you want to change how addition works, you only change it in one place.


Why Functions Matter — Summary

Without functions:

  • Code is repeated everywhere
  • Hard to fix bugs — you have to fix the same thing in 10 places
  • Hard to read and understand

With functions:

  • Write once, use anywhere
  • Fix in one place — fixed everywhere
  • Code is organized and readable

This principle is called DRY — Don't Repeat Yourself. It's one of the most important principles in programming.


Exercise 🏋️

Build a Student Grade Calculator using functions:

Create these functions:

  1. get_average(marks) — takes a list of 5 subject marks as separate parameters and returns the average
  2. get_grade(average) — takes average and returns grade (A/B/C/D/F using same logic as before)
  3. print_report(name, average, grade) — prints a formatted report card

Then write a main program that:

  • Asks for student name
  • Asks for marks in 5 subjects
  • Calls all three functions and displays the report

Expected output:

=== Report Card ===
Student: Gagan
Marks: 85, 90, 78, 92, 88
Average: 86.6
Grade: B
===================

No comments:

Post a Comment

Functions in Python

What is a Function? The Problem Without Functions Look at this program:     # Calculating area of rectangle 1     length1 = 10     width...