Functions in Python
Written and reviewed by Gagan Bhardwaj · Senior IT Faculty · 15+ years’ experience
What is a Function?
A function is a reusable block of code that does one job. Write it once, call it many times. This keeps programs short, organized and easy to fix.
Instead of copying the same 5 lines in 10 places, you put them in a function and call it. One fix updates everywhere — this is the heart of clean B.Tech-level code.
Defining a Function
Use the def keyword, a name, brackets, and a colon. The indented block is the body.
def say_hello():
print("Hello!")
say_hello() # call it
say_hello() # call againParameters & Arguments
A function can accept inputs (parameters). The values you pass in are arguments.
def greet(name):
print("Hello,", name)
greet("Aman")
greet("Riya")Return Values
return sends a result back to the caller so it can be stored or reused.
def square(n):
return n * n
result = square(5)
print(result)Program 1: Greeting Function
def greet(name, time):
print(f"Good {time}, {name}!")
greet("Aman", "morning")
greet("Riya", "evening")Program 2: Area Calculator
def rectangle_area(length, width):
return length * width
def circle_area(radius):
return 3.14 * radius * radius
print("Rectangle:", rectangle_area(10, 5))
print("Circle :", circle_area(7))Two small functions, each doing one calculation and returning the answer.
Program 3: Default & Keyword Arguments
def power(base, exp=2): # exp defaults to 2
return base ** exp
print(power(5)) # uses default exp=2
print(power(2, 3)) # exp=3
print(power(exp=4, base=2)) # keyword argsexp=2is a default — used if you do not pass it.- You can pass arguments by name (keyword) in any order.
Program 4: Factorial Function
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print("5! =", factorial(5))
print("0! =", factorial(0))Program 5: *args — Any Number of Inputs
def total(*numbers): # *args collects all into a tuple
return sum(numbers)
print(total(10, 20))
print(total(1, 2, 3, 4, 5))*numbers lets the function accept any count of values, gathered into a tuple.
Local vs Global Variables
- A variable made inside a function is local — it exists only there.
- A variable made outside is global — visible everywhere.
- To change a global from inside, use the
globalkeyword.
Common Mistakes
- Forgetting
return— the function then givesNone. - Defining a function but never calling it.
- Wrong number of arguments passed.
- Confusing
print(shows) withreturn(gives back).
Practice Tasks
- Write a function that returns the larger of two numbers.
- Write a function to check if a number is prime.
- Write a function that takes a name and an optional greeting (default "Hello").
- Write a function using
*argsto find the average of any numbers.
Summary
- Functions are reusable code blocks defined with
def. - Parameters receive inputs;
returnsends back a result. - Defaults, keyword args and
*argsmake functions flexible. - Variables inside a function are local by default.