- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Python Function Introduction
A function in Python is a block of reusable code that performs a specific task. Functions help organize code, reduce repetition, and improve readability.
1. Why Use Functions?
✔ Avoid repeating code
✔ Break large programs into small logical pieces
✔ Improve readability and maintainability
✔ Make code scalable and easier to debug
2. Defining and Calling a Function
Syntax
def function_name(parameters):
# code block
return value
Example
def greet():
print("Hello, welcome to Python!")
greet() # Calling the function
3. Function with Parameters (Arguments)
def greet_user(name):
print("Hello", name)
greet_user("John")
Output
Hello John
4. Function with Return Value
def add(x, y):
return x + y
result = add(10, 5)
print(result)
Output
15
5. Default Parameters
If no value is passed, default will be used.
def info(country="India"):
print("I am from", country)
info()
# output : I am from India
info("Japan")
# output : I am from Japan
6. Keyword Arguments
Arguments can be passed using the parameter name.
def student(name, age):
print(name, "is", age, "years old")
student(age=21, name="Riya")
# Output : Riya is 21 year old.
7. Arbitrary Arguments (*args)
Used when you don’t know how many arguments will be passed.
def total_marks(*marks):
print("Total:", sum(marks))
total_marks(80, 75, 90, 60)
# Output : Total : 305
8. Arbitrary Keyword Arguments (**kwargs)
Accepts key-value pairs (dictionary-like).
def profile(**details):
for key, value in details.items():
print(key, ":", value)
profile(name="Amit", age=25, city="Delhi")
# Output :
name : Amit
age : 25
city : Delhi
9. Lambda (Anonymous) Functions
Short, one-line functions without a name.
square = lambda x: x * x
print(square(6))
# Output : 36
10. Nested Functions
Function inside another function.
def outer():
print("Outer Function")
def inner():
print("Inner Function")
inner()
outer()
11. Recursion (Function Calling Itself)
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
# Output : 120
12. Passing a Function as an Argument
def apply(func, value):
return func(value)
def double(x):
return x * 2
print(apply(double, 4)) # Output: 8
Best Practices
| Practice | Description |
|---|---|
| Use meaningful names | calculate_total() is better than ct() |
| Keep functions short | One task per function |
| Document your function | Write comments or use docstrings |
| Avoid global variables | Prefer passing parameters |
Docstring Example
def multiply(a, b):
"""Returns the product of two numbers"""
return a * b
print(multiply.__doc__)