Day 5 - Python Lect 4
Day 5 - Python Lect 4
Language
MICROSOFT AI-102 COURSE
DAY 5
PYTHON LECT # 4
1
Agenda
Function
Variable Scope
Recursion
Lambda Expression
Map
Filter
Nested Function
File Handling
2
Function
A function is a block of code that can be executed multiple times
from different parts of your program. It's a way to group a set of
statements together to perform a specific task.
Why to use function?
Code Reusability
Modular Approach
Easy Debugging
3
Define Function
def: Keyword used to declare a function.
Function name: The name of the function.
parameters: A list of parameters (arguments) that the function can
accept.
statement(s): Block of code that executes when the function is
called.
return: A function can return value using return statement.
4
Example
def greet(name):
print("Hello, " + name + "!")
greet(“Kim") # Call to function greet()
5
Variable-Length Arguments
It is a way to pass a variable number of arguments to a
function. This allows the function to accept any number of
arguments.
There are 2 types:
*args (non-keyword arguments)
**kwargs (keyword arguments)
6
*args (non-keyword arguments)
- Allows passing a variable number of positional arguments.
- The arguments are collected into a tuple called args.
# This function returns the sum of all arguments.
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(1, 2, 3, 4)) # Output: 10
7
**kwargs (keyword arguments)
- Allows passing a variable number of keyword arguments.
- The arguments are collected into a dictionary called kwargs.
# This function prints info send as keyword args
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name=“Omer”, age=30, city="New York")
display_info(age=11, name="Ali", city="Bwp")
8
Variable Scope
Scope of a variable refers to the region of the code where the variable is defined
and can be accessed.
Local scope: Variables defined within a function have local scope, meaning they
can only be accessed within that function. They are created when the function is
called and destroyed when the function finishes execution.
def my_function():
x = 20 # local variable
print("Local x:", x)
my_function()
print("Global x:", x) # Local x: 20 Global x: 10
10
Example
z = 30 # z is a global variable
def my_function(z): # z is local variable here
z=z+5
print(z) # Output: 35
my_function(z)
print(z) # Output: 30
11
Example
If you want to modify a global variable within a function,
you need to use the global keyword:
x = 10 # global variable
def my_function():
global x
x = 20 # modify global variable
print(“Modified Global x:", x)
my_function()
print("Global x:", x) # Modified Global x: 20 Global x: 10
12
Recursion
When a function calls itself directly or indirectly in order to solve a problem.
Base Case: The condition under which the recursion ends. Without a base
case, the recursion would continue indefinitely, leading to a stack overflow.
Recursive Case: The part of the function where the function calls itself with a
modified argument, moving towards the base case.
13
Exmp
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
factorial(5) # output 120
14
Lambda Expression
Lambda expression in Python is a small, anonymous function
that can take any number of arguments, but can only have
one expression. It's a shorthand way to define a function
without declaring it with the def keyword.
double = lambda x: x * 2
print(double(5)) # output: 10
add_lambda = lambda x, y: x + y
print(add_lambda(2, 3)) # Output: 5
15
Map Function
A map is a built-in function that applies a given function to each item
of an iterable (such as a list, tuple, or dictionary) and returns a map
object, which is an iterator.
The general syntax is:
map(function, iterable)
function is the function you want to apply to each item-
iterable is the list, tuple, or other iterable you want to apply the
function
16
Map Function Exmp
# Map with lambda
numbers = [1, 2, 3, 4, 5]
Squared_numbers_lambda = list(map(lambda x: x**2, numbers))
print(squared_numbers_lambda) # Output: [1, 4, 9, 16, 25]
18
Example
# with lambda
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
# without lambda
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(is_even, numbers))
print(even_numbers)
19
Q&A
20