Free Study Material

Functions In Python

What is a Function?

Think of a Function as a mini-program inside your main program. A Function is an isolated block of code that does exactly one specific job, and it has its own name.

Instead of typing the exact same code over and over again, you write it just once. Whenever you want Python to do that job, you simply call the Function's name.

Why Do We Need Functions?

01

Save Time (Reusability)

Write it once, use it forever. Instead of copy-pasting the same 10 lines of code everywhere, you just type the function's name whenever you need it.

02

Break it Down (Modularity)

Huge programs can be confusing. Functions let you chop a massive, scary script into small, organized chunks that are much easier to read and understand.

03

Easy Bug Fixing

If your code has a mistake and you copy-pasted it 50 times, you have to fix it 50 times! With a function, you fix the mistake in one place, and it is instantly fixed everywhere.

def start_engine():
    print("Vroom! Engine started.")
    print("System ready.")

# The function is defined above, but nothing runs yet.
# TODO: Call start_engine() below this line to make it work.
start_engine()
def wish_birthday(friend_name):
    # TODO: Use the friend_name variable inside the print statement
    print("Happy Birthday, ") 

# TODO: Call the function below with the name "Amit"
wish_birthday("Amit")

The 3 Types of Functions

In Python, we have three different types of functions. They are categorized simply by where they come from and who created them.

1. Built-in

These functions are already made by Python. They are always ready to use immediately, without you having to do any extra work.

print()

2. In Modules

These are also made by Python, but they are saved in special folders called "modules". You must import them into your code first.

math.sqrt()

3. User-Defined

These are the custom functions that you write yourself using the def keyword to do exactly what you want.

def my_function():
def say_hello():
    print("Welcome to KV Coders!")
    print("This is your very first custom function.")

say_hello()

How Python Reads a Function

Normally, Python reads code from top to bottom, one line at a time. But when you create a function, Python changes its rules.

Step 1: Skipping the Definition

When Python sees the word def, it reads the name of the function and memorizes it. But it does not run the code inside the block. It skips right past it.

Step 2: Jumping on the Call

Python only runs the code when you specifically type the Function Call at the bottom. When it hits the call, Python jumps up, runs the saved code, and then jumps right back down to finish the script.

def my_function():
    print("2. Inside Function ")

print("1. Start of program")
my_function() # The Jump happens here
print("3. End of program")

# TODO: Add a new print statement INSIDE the function to see it appear in the middle.
def first_place_winner():
    print("You won a Gold Medal!")


first_place_winner()

Parameters vs. Arguments

A parameter is the variable named in a function's definition; an argument is the value you pass when you call the function. In def get_area(base, height):, base and height are parameters; in get_area(10, 5), 10 and 5 are the arguments. For CBSE Class 12 you need two kinds: positional arguments, matched to parameters strictly by their order, and default arguments, where a parameter is given a backup value in the definition (such as exp=2) so the argument can be left out of the call. The CBSE syllabus calls these positional and default parameters.

1. Parameters (The Variables)

When you define a function, you write variable names inside the parentheses (). These are your parameters. They are just empty variables waiting to receive data.

In the code below: name and age are the parameters.

def register(name, age):

2. Arguments (The Real Values)

When you use the function, you give it real data (like a real name or a real number). These real values go inside the parentheses and are called arguments.

In the code below: "Rahul" and 17 are the arguments.

register("Rahul", 17)
def introduce(name, age):
    print("Name: " + name)
    print("Age: " + str(age))
    print("---")

# The order matters! First goes to name, second goes to age.
introduce("Rahul", 17)
introduce("Priya", 16)
def power(base, exp=2):
    print(base ** exp)

# Uses default exp=2 (5 squared)
power(5)

# Overrides exp to 3 (5 cubed)
power(5, 3)
def calculate_interest(principal, rate):
    print((principal * rate) / 100)

# Positional (Order matters)
calculate_interest(1000, 5)

# Keyword (Order does not matter because we name them)
calculate_interest(rate=5, principal=1000)
def multiply_all(*numbers):
    result = 1
    for n in numbers:
        result = result * n
    print(result)

# Pass two numbers
multiply_all(5, 2)

# Pass four numbers
multiply_all(2, 3, 4, 5)

Global vs. Local Scope

Variables in Python have strict privacy rules called Scope. This rule determines where a variable can be seen or used in your code. There are two main places a variable can live: inside a function, or outside in the main program.

1. Local Scope (Inside)

If you create a variable inside a function, it is Local. It only exists while that function is running. The main program outside cannot see it or use it.

def my_func(): # x is local. Hidden from outside. x = 10 print(x)

2. Global Scope (Outside)

If you create a variable outside of all functions (in the main program), it is Global. It is public. Any function can look outside and read its value.

# y is global. Visible everywhere. y = 20 def my_func(): print(y)
score = 100

def show_data():
    bonus = 50
    print(score)
    print(bonus)

show_data()
print(score)
# print(bonus)

The 'global' Keyword

By default, a function can read a global variable, but it cannot change it. To modify a global variable from inside a function, you must use the global keyword.

The Problem: Accidental Locals

If you try to change a global variable inside a function without the keyword, Python gets confused. Instead of updating the global variable, it creates a brand new local variable with the same name. The global one stays exactly the same.

The Solution: The 'global' Declaration

When you type global variable_name inside your function, you are telling Python: "Don't create a new variable. I want to use the one that already exists outside."

count = 10

def update_score():
    global count  # Tell Python we are using the global 'count'
    count = count + 5
    print("Inside function:", count)

update_score()
print("Outside function:", count)
# Notice: We DO NOT create 'high_score' out here.

def set_initial_score():
    # Tell Python to make this global, even though it doesn't exist yet
    global high_score 
    high_score = 500
    print("Inside function: high_score is created and set to", high_score)

# 1. Run the function so it creates the variable
set_initial_score()

# 2. Now the main program can safely read it!
print("Outside function: high_score is", high_score)

Want the full course?

Unlock all chapters, video lectures, and SQL practice exercises.

Get Full Access