Functions in Python
A function is a reusable block of code that performs a specific task.
Instead of writing the same code again and again, we can write it once inside a function and call it whenever needed.
1. Creating a Function
Python uses the def keyword to create a function.
Syntax
def function_name(): # code
Example
def greet(): print("Hello, Python!") greet()
Output:
Hello, Python!
Here:
def→ defines a functiongreet→ function name()→ parameters go here:→ starts the function blockgreet()→ calls the function
2. Function with Parameters
A parameter is a value that a function receives.
def greet(name): print("Hello", name) greet("Uday")
Output:
Hello Uday
Here, name is a parameter.
3. Multiple Parameters
A function can have multiple parameters.
def add(a, b): print(a + b) add(10, 20)
Output:
30
4. Arguments
The actual values passed to a function are called arguments.
def student(name, age): print(name) print(age) student("Ram", 20)
Here:
name,age→ parameters"Ram",20→ arguments
5. return Statement
The return statement sends a value back from a function.
def add(a, b): return a + b result = add(10, 20) print(result)
Output:
30
Difference
Using print():
def add(a, b): print(a + b)
Using return:
def add(a, b): return a + b
return allows us to store and reuse the result.
6. Function Without Parameters
def message(): return "Welcome to Python" print(message())
Output:
Welcome to Python
7. Default Arguments
A parameter can have a default value.
def greet(name="Student"): print("Hello", name) greet() greet("Ram")
Output:
Hello Student Hello Ram
If no argument is provided, "Student" is used.
8. Keyword Arguments
We can pass arguments using parameter names.
def student(name, age): print(name, age) student(age=20, name="Ram")
Output:
Ram 20
The order does not matter when using keyword arguments.
9. Positional Arguments
Arguments can also be passed according to their position.
def student(name, age): print(name) print(age) student("Ram", 20)
Here:
"Ram" → name 20 → age
10. Variable-Length Arguments
Sometimes we don't know how many arguments will be passed.
*args
*args allows multiple positional arguments.
def add(*numbers): print(sum(numbers)) add(10, 20, 30, 40)
Output:
100
**kwargs
**kwargs allows multiple keyword arguments.
def student(**details): print(details) student(name="Ram", age=20, city="Janakpur")
Output:
{'name': 'Ram', 'age': 20, 'city': 'Janakpur'}
kwargs stores the values as a dictionary.
11. Returning Multiple Values
A function can return multiple values.
def calculate(a, b): return a + b, a - b x, y = calculate(20, 10) print(x) print(y)
Output:
30 10
Python returns them as a tuple.
12. Local Variables
A variable created inside a function is called a local variable.
def test(): x = 10 print(x) test()
x can normally be accessed only inside the function.
13. Global Variables
A variable created outside a function is called a global variable.
x = 10 def show(): print(x) show()
Output:
10
The function can read the global variable.
14. Changing a Global Variable
Use the global keyword when you need to modify a global variable inside a function.
count = 0 def increase(): global count count += 1 increase() print(count)
Output:
1
15. Function Calling Another Function
One function can call another function.
def add(a, b): return a + b def show_result(): result = add(10, 20) print(result) show_result()
Output:
30
16. Recursive Function
A function that calls itself is called a recursive function.
Example: factorial
def factorial(n): if n == 1: return 1 return n * factorial(n - 1) print(factorial(5))
Output:
120
The function keeps calling itself until the stopping condition is reached.
17. Lambda Function
A lambda is a small anonymous function.
Normal function
def square(x): return x * x
Lambda
square = lambda x: x * x print(square(5))
Output:
25
Lambda functions are useful for short operations.
18. Built-in vs User-Defined Functions
Built-in Functions
Python already provides many functions.
print() len() type() sum() max() min() range() input()
Example:
numbers = [10, 20, 30] print(len(numbers)) print(sum(numbers))
User-Defined Functions
Functions created by the programmer.
def welcome(): print("Welcome")
19. Docstring
A docstring describes what a function does.
def add(a, b): """Returns the sum of two numbers.""" return a + b
You can view it using:
print(add.__doc__)
Output:
Returns the sum of two numbers.
20. Function Example
def calculate_total(price, quantity): total = price * quantity return total price = 100 quantity = 5 result = calculate_total(price, quantity) print("Total:", result)
Output:
Total: 500
Function Structure
def function_name(parameters): | ↓ Function Body | ↓ return value
Example:
def add(a, b): return a + b
def → create function add → function name a, b → parameters return → send result back a + b → returned value
Types of Functions
| Type | Example |
|---|---|
| No parameter, no return | def hello(): |
| Parameter, no return | def hello(name): |
| No parameter, return | def get_name(): |
| Parameter and return | def add(a, b): |
| Default parameter | def greet(name="Student"): |
| Variable arguments | def add(*numbers): |
| Keyword arguments | def student(**details): |
| Lambda function | lambda x: x * 2 |
| Recursive function | Function calling itself |
Key Points
- Use
defto create a function. - Use
()to pass parameters and arguments. - Use
returnto send a result back. - Functions reduce code repetition.
- Functions make programs organized, reusable, and easier to maintain.