๐ฐ What Is a Function?

A function is a reusable block of code that performs a specific task.
Instead of repeating code, we can write it once and call it whenever needed.
โ๏ธ Defining a Function
def greet():
print("Hello, welcome to Python!")
greet()
โ Output:
Hello, welcome to Python!
๐ฏ Functions with Parameters
Functions can accept parameters (inputs).
def greet(name):
print(f"Hello, {name}!")
greet("Ali")
greet("Sara")
โ Output:
Hello, Ali!
Hello, Sara!
๐ฏ Functions with Return Values
Functions can return data using return
.
def add(a, b):
return a + b
result = add(5, 3)
print("The sum is:", result)
โ Output:
The sum is: 8
๐ Default Parameters
You can assign default values to parameters.
def greet(name="Friend"):
print(f"Hello, {name}!")
greet() # uses default
greet("Omar") # overrides default
โ Output:
Hello, Friend!
Hello, Omar!
๐ Variable Scope (Local vs Global)
- Local variable: exists only inside a function.
- Global variable: exists everywhere in the program.
x = 10 # global variable
def test():
x = 5 # local variable
print("Inside function:", x)
test()
print("Outside function:", x)
โ Output:
Inside function: 5
Outside function: 10
๐ฆ Lambda (Anonymous Functions)
Quick one-line functions using lambda
.
square = lambda x: x * x
print(square(4))
โ Output:
16
๐ง Exercise 1: Calculator Functions
- Write functions:
add
,subtract
,multiply
,divide
. - Ask the user for two numbers.
- Use the functions to print results.
๐ง Exercise 2: Scope
- Create a global variable
counter = 0
. - Write a function that increases the counter.
- Show the difference between modifying it locally vs globally.
๐ Summary
- Functions help us organize and reuse code.
- Use parameters to pass values and
return
to get results. - Scope determines where variables can be accessed.
- Lambda functions are quick, single-line functions.