python functions
Python Functions
Introduction
As programs grow larger, repeating the same code multiple times becomes difficult to manage.
Example:
print("Welcome to Python")
print("Welcome to Python")
print("Welcome to Python")
If we need this message in many places, repeating code is inefficient.
Functions solve this problem.
What is a Function?
A function is a reusable block of code designed to perform a specific task.
Think of a function as a machine:
Input
↓
Function
↓
Output
Example:
def greet():
print("Welcome to Python")
The function can be used multiple times.
Why Use Functions?
Functions help us:
- Reuse code
- Reduce duplication
- Improve readability
- Improve maintainability
- Organize programs
- Simplify debugging
Real World Example
Without Functions:
print(10 + 20)
print(30 + 40)
print(50 + 60)
With Functions:
def add(a, b):
print(a + b)
add(10, 20)
add(30, 40)
add(50, 60)
Output:
30
70
110
Function Basics
A function has two main parts:
- Function Definition
- Function Call
Example:
def greet():
print("Hello")
Definition only creates the function.
To execute it:
greet()
Output:
Hello
Defining a Function
Syntax
def function_name():
statements
Explanation:
| Part | Meaning |
|---|---|
| def | Keyword to define function |
| function_name | Name of function |
| () | Parameter area |
| : | Start of function block |
| statements | Code to execute |
Example
def welcome():
print("Welcome to Python")
Function created.
Nothing executes yet.
Function Call
What is a Function Call?
Calling a function means executing it.
Example:
def welcome():
print("Welcome")
welcome()
Output:
Welcome
Multiple Function Calls
def greet():
print("Hello")
greet()
greet()
greet()
Output:
Hello
Hello
Hello
Function Execution Flow
Program Starts
|
V
Function Defined
|
V
Function Called
|
V
Function Executes
|
V
Returns Control
Example: Calculator Function
def add_numbers():
print(10 + 20)
add_numbers()
Output:
30
Return Statement
What is return?
The return statement sends a value back from a function.
Without return:
def add():
result = 10 + 20
print(result)
Output:
30
Value is printed but not returned.
Function with Return
def add():
result = 10 + 20
return result
answer = add()
print(answer)
Output:
30
Why Use return?
A returned value can be:
- Stored in variables
- Passed to other functions
- Used in calculations
Example:
def square(number):
return number * number
result = square(5)
print(result)
Output:
25
Returning Expressions
def add(a, b):
return a + b
print(add(10, 20))
Output:
30
Returning Multiple Values
Python allows returning multiple values.
def student():
name = "John"
age = 20
return name, age
data = student()
print(data)
Output:
('John', 20)
Unpacking Multiple Returns
def student():
return "John", 20
name, age = student()
print(name)
print(age)
Output:
John
20
Function Without Return
def hello():
print("Hello")
Python automatically returns:
None
Example:
def hello():
print("Hello")
result = hello()
print(result)
Output:
Hello
None
Function Parameters
What are Parameters?
Parameters are variables listed in the function definition.
Example:
def greet(name):
print("Hello", name)
Here:
name
is a parameter.
Why Use Parameters?
Without parameters:
def greet():
print("Hello John")
Only works for John.
With parameters:
def greet(name):
print("Hello", name)
Now it works for anyone.
Example
def greet(name):
print("Hello", name)
greet("Rahul")
greet("John")
greet("Alice")
Output:
Hello Rahul
Hello John
Hello Alice
Multiple Parameters
def add(a, b):
print(a + b)
add(10, 20)
Output:
30
Three Parameters Example
def student(name, age, city):
print(name)
print(age)
print(city)
student("John", 20, "Delhi")
Output:
John
20
Delhi
Parameter vs Argument
One of the most important interview questions.
Parameter
A parameter is a variable inside the function definition.
Example:
def greet(name):
print(name)
Here:
name
is a parameter.
Argument
An argument is the actual value passed during a function call.
Example:
greet("Rahul")
Here:
"Rahul"
is an argument.
Comparison Table
| Parameter | Argument |
|---|---|
| Defined in function | Passed during call |
| Placeholder | Actual value |
| Receives data | Sends data |
| Exists in definition | Exists in call |
Visual Understanding
def greet(name):
print(name)
Parameter:
name
Function Call:
greet("John")
Argument:
"John"
Flow:
Argument
↓
Parameter
↓
Function
Multiple Arguments Example
def add(a, b):
print(a + b)
add(10, 20)
Parameters:
a
b
Arguments:
10
20
Local Variables Inside Functions
Variables created inside a function are local.
def demo():
x = 10
print(x)
demo()
Output:
10
Local Variable Error
❌ Wrong
def demo():
x = 10
demo()
print(x)
Output:
NameError
Returning Values vs Printing Values
Using print()
def add():
print(10 + 20)
add()
Output:
30
Cannot reuse result easily.
Using return()
def add():
return 10 + 20
result = add()
print(result * 2)
Output:
60
Return is usually more useful.
Common Function Mistakes
Mistake 1: Defining but Not Calling
❌ Wrong
def greet():
print("Hello")
Output:
Nothing
✅ Correct
greet()
Mistake 2: Missing Parentheses
❌ Wrong
greet
Output:
Function Reference
✅ Correct
greet()
Mistake 3: Missing Return
❌ Wrong
def add():
10 + 20
Output:
None
✅ Correct
def add():
return 10 + 20
Mistake 4: Wrong Number of Arguments
❌ Wrong
def add(a, b):
print(a + b)
add(10)
Output:
TypeError
✅ Correct
add(10, 20)
Mistake 5: Accessing Local Variable Outside Function
❌ Wrong
def test():
value = 100
print(value)
Output:
NameError
Mistake 6: Confusing Parameter and Argument
❌ Wrong Understanding
def add(a, b):
Thinking:
10 and 20 are parameters
Actually:
a and b = Parameters
10 and 20 = Arguments
Best Practices
Use Meaningful Names
❌ Avoid
def x():
✅ Better
def calculate_total():
Keep Functions Focused
❌ Avoid
def everything():
✅ Better
def calculate_tax():
def generate_invoice():
Prefer return Over print
Good:
def square(n):
return n * n
Homework 1
Create a function that prints:
Welcome to Python
Solution
def welcome():
print("Welcome to Python")
welcome()
Homework 2
Create a function that adds two numbers.
Solution
def add(a, b):
return a + b
print(add(10, 20))
Output:
30
Homework 3
Create a function that calculates the square of a number.
Solution
def square(number):
return number * number
print(square(5))
Output:
25
Homework 4
Create a function that prints student details.
Parameters:
name
age
city
Solution
def student(name, age, city):
print(name)
print(age)
print(city)
student("John", 20, "Delhi")
Homework 5
Create a function that returns:
name
age
and unpack the values.
Solution
def person():
return "John", 20
name, age = person()
print(name)
print(age)
Output:
John
20
Homework 6
Create a function that checks whether a number is even.
Solution
def is_even(number):
if number % 2 == 0:
return True
return False
print(is_even(10))
Output:
True
Homework 7
Create a function that returns the larger of two numbers.
Solution
def maximum(a, b):
if a > b:
return a
return b
print(maximum(10, 20))
Output:
20
Quick Revision
| Concept | Meaning |
|---|---|
| Function | Reusable block of code |
| def | Creates function |
| Function Call | Executes function |
| return | Sends value back |
| Parameter | Variable in definition |
| Argument | Value passed to function |
| Local Variable | Exists only inside function |
Function Flow
Define Function
|
V
Call Function
|
V
Pass Arguments
|
V
Receive Parameters
|
V
Execute Code
|
V
Return Value
|
V
Continue Program
Summary
| Topic | Description |
|---|---|
| Function | Reusable code block |
| def | Function definition keyword |
| Function Call | Runs the function |
| return | Sends value back |
| Parameter | Placeholder variable |
| Argument | Actual supplied value |
| Local Variable | Exists only inside function |
| Multiple Returns | Return more than one value |
| None | Default return value |
Functions are one of the most important concepts in Python and form the foundation for:
- Modular Programming
- Object-Oriented Programming
- APIs
- Django Development
- Flask Development
- Automation Scripts
- Data Science
- Machine Learning
Master these basics before learning:
- Types of Function Arguments
- Default Parameters
- Keyword Arguments
- Variable-Length Arguments (
*args,**kwargs) - Lambda Functions
- Recursion
- Higher-Order Functions
- Decorators