A function is a named block of reusable code that performs a specific task. Instead of writing the same code repeatedly, you define it once in a function and call it whenever needed.
Functions help in:
| Type | Description |
|---|---|
| Built-in Functions | Pre-defined in Python, e.g. print(), input(), len(), range() |
| User-defined Functions | Created by the programmer using the def keyword |
Use the def keyword followed by the function name and parentheses:
def function_name(parameters):
# body of the function
statement(s)
Example:
def greet():
print("Hello, World!")
greet() # calling the function
Output:
Hello, World!
def greet(name): # 'name' is a parameter
print("Hello,", name)
greet("Ali") # 'Ali' is an argument
greet("Sara")
Output:
Hello, Ali
Hello, Sara
def add(a, b):
print(a + b)
add(3, 5) # Output: 8
return StatementA function can return a value to the caller using the return statement.
def square(n):
return n * n
result = square(4)
print(result) # Output: 16
return is executed, the function ends.return statement returns None by default.You can assign a default value to a parameter. If no argument is passed, the default is used.
def greet(name="Guest"):
print("Hello,", name)
greet() # Output: Hello, Guest
greet("Ahmed") # Output: Hello, Ahmed
x = 10 # global variable
def show():
y = 5 # local variable
print(x) # can access global x
print(y)
show()
# print(y) # Error! y is not accessible here
Functions allow you to decompose (break down) a complex problem into smaller, manageable sub-problems.
Example — Calculate area and perimeter of a rectangle:
def area(length, width):
return length * width
def perimeter(length, width):
return 2 * (length + width)
l = 5
w = 3
print("Area:", area(l, w)) # Output: Area: 15
print("Perimeter:", perimeter(l, w)) # Output: Perimeter: 16
Each sub-problem (area, perimeter) is solved independently in its own function.
| Concept | Key Point |
|---|---|
def keyword | Used to define a function |
| Parameter | Variable in function definition |
| Argument | Value passed during function call |
return | Sends a value back to the caller |
| Default parameter | Used when no argument is provided |
| Local variable | Exists only inside the function |
| Global variable | Accessible throughout the program |