After variables, operators, conditions, and loops, the next important concept is functions.
Functions help you organize code, avoid repetition, and make programs easier to understand and maintain.
๐ง 1. What is a Function?
A function is a reusable block of code designed to perform a specific task.
Instead of writing the same code repeatedly, you can put it inside a function and call it whenever you need it.
For example:
def greet():
print("Hello!")
greet()
Output:
Hello!
๐ฏ 2. Why Do We Use Functions?
Functions help with:
โ Code reusability
โ Better organization
โ Easier debugging
โ Readability
โ Maintaining large programs
A good function usually focuses on one clear task.
๐ฅ 3. Function Parameters
Functions can accept information from the code that calls them.
def greet(name):
print("Hello", name)
greet("Alex")
Output:
Hello Alex
Here, "name" is a parameter.
"Alex" is the argument passed to the function.
๐ค 4. Returning a Value
A function can return a result instead of directly displaying it.
def add(a, b):
return a + b
result = add(10, 5)
print(result)
Output:
15
"return" sends the result back to the place where the function was called.
๐ 5. Parameters vs Arguments
These two terms are often confused.
In:
def add(a, b):
return a + b
"a" and "b" are parameters.
In:
add(10, 5)
"10" and "5" are arguments.
Parameter โ Variable defined by the function
Argument โ Actual value passed to the function
โ๏ธ 6. Default Parameters
A function can have a default value for a parameter.
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Alex")
Output:
Hello Guest
Hello Alex
If no argument is provided, the default value is used.
๐ 7. Functions in Different Languages
The syntax changes between languages, but the concept remains similar.
Python
def add(a, b):
return a + b
JavaScript
function add(a, b) {
return a + b;
}Java
static int add(int a, int b) {
return a + b;
}C++
int add(int a, int b) {
return a + b;
}The purpose is the same: define reusable logic that can be called when needed.
๐ง 8. Local Variables
A variable created inside a function is generally local to that function.
def calculate():
result = 100
print(result)
calculate()
Here, "result" belongs to the function's local scope.
Understanding scope becomes especially important as programs become larger.
๐ 9. Functions Can Call Other Functions
One function can use another function.
def add(a, b):
return a + b
def show_result():
result = add(10, 20)
print(result)
show_result()
This allows larger programs to be broken into smaller, manageable pieces.
๐งฉ 10. Functions and Loops
Functions and loops are often used together.
def print_numbers():
for i in range(1, 6):
print(i)
print_numbers()
The function organizes the task, while the loop handles repetition.
๐ฅ Double Tap โค๏ธ For More