Skip to content

Commit 16c731a

Browse files
committed
Funtion has been added
1 parent 83de032 commit 16c731a

4 files changed

Lines changed: 59 additions & 0 deletions

File tree

04-functions/README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
## Overview
3+
Functions are fundamental building blocks in Python programming that allow you to group code into reusable chunks.
4+
We can defined using the `def` keyword and can take parameters and return values.
5+
6+
## Files
7+
8+
- `basic_functions.py`: Contains examples of defining and using basic functions.
9+
- `scope_lifetime.py`: Illustrates how variable scope and lifetime work in Python.
10+
- `higher_order_functions.py`: Shows examples of higher-order functions, including functions that take other functions as arguments and return functions.
11+

04-functions/basic_functions.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
def add_numbers(a, b): #funtion declaration
2+
return a + b
3+
4+
5+
def greet(name): # funtion declaration
6+
print(f"Hello, {name}!")
7+
8+
result = add_numbers(3, 5) # fuuntion calling
9+
print(f"Sum: {result}")
10+
11+
greet("Bob") # function calling
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
def apply_function(func, value): #function that takes another function as an argument
3+
return func(value)
4+
5+
6+
def square(x):
7+
return x * x
8+
9+
def double(x):
10+
return x * 2
11+
12+
number = 4
13+
print(f"The square of {number} is {apply_function(square, number)}")
14+
print(f"The double of {number} is {apply_function(double, number)}")
15+
16+
17+
def make_multiplier(factor): # function that returns another function
18+
def multiplier(x):
19+
return x * factor
20+
return multiplier
21+
22+
times_three = make_multiplier(3)
23+
print(f"5 times 3 is {times_three(5)}")

04-functions/scope_lifetime.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
global_var = "I'm a global variable" # a global variable
3+
4+
def my_function():
5+
6+
local_var = "I'm a local variable" # Local variable
7+
print(global_var) # accessing global variable
8+
print(local_var) # accessing local variable
9+
10+
11+
my_function() # calling funtion
12+
13+
# This will raise an error because local_var is not accessible outside the function
14+
# print(local_var) # uncommenting this line will cause an error

0 commit comments

Comments
 (0)