Functions in Python
1. What is a Function?
A function in Python is a block of reusable code that performs a specific task. Functions help in
breaking large programs into smaller, manageable parts, making the code easier to read, debug,
and maintain.
2. Why Use Functions?
- Code reusability
- Better organization of code
- Easy debugging and testing
- Improves readability
3. Types of Functions in Python
Python supports two main types of functions:
1. Built-in functions (e.g., print(), len(), type())
2. User-defined functions
4. Defining a Function
A function is defined using the def keyword followed by the function name and parentheses.
Syntax:
ife
def function_name(parameters):
statement(s)
al
Example:
pa
def greet():
print("Hello, Welcome to Python")
ru
5. Function with Parameters
Parameters are values passed to a function to perform a specific task.
Example:
def add(a, b):
print(a + b)
add(5, 3)
6. Function with Return Value
The return statement is used to send a result back to the caller.
Example:
def square(num):
return num * num
result = square(4)
print(result)
7. Default Arguments
Default arguments allow a function to use a default value if no argument is passed.
Example:
def greet(name="Student"):
print("Hello", name)
greet()
greet("Rupa")
8. Key Points to Remember
- Functions are defined using def keyword
- Function name should be meaningful
- Use return to send values back
- Functions make code reusable and clean
ife
al
pa
ru