Chapter 4 Python
Chapter 4 Python
Functions
Eyob S.
SITE, AAiT
1 Introduction
2 Types of Functions
4 Variable Scopes
Introduction
Defining a Function:
def function_name(parameters):
"""
Docstring (optional)
"""
# Function body
return result
Calling a Function:
result = function_name(arguments)
Types of Functions
Python provides many built-in functions that are always available. Here are
some of the most commonly used:
math random
sys re
itertools functools
os collections
datetime json
heapq operator
import math
The random module provides functions for generating random numbers and
performing random operations.
import random
# Random float between 0.0 and 1.0
print(random.random())
# Random integer between 1 and 10
print(random.randint(1, 10))
# Random choice
print(random.choice(['apple', 'banana', 'cherry']))
# 5 unique random numbers
print(random.sample(range(100), 5))
The datetime module supplies classes for manipulating dates and times.
import datetime
now = datetime.datetime.now()
print(now) # Output: Current date and time
new_year = datetime.datetime(2024, 1, 1)
print(new_year) # Output: 2024-01-01 00:00:00
The os module provides functions for interacting with the operating system.
import os
def greet(name):
return f"Hello, {name}!"
If you try to assign the result to a variable, you get a special value
called None.
def print_message():
print("Hello, World!")
result = print_message()
print(result)
print(print_message())
result = add(3, 5)
print(result)
def is_even(n):
return n % 2 == 0
print(is_even(4))
print(is_even(7))
Used for problems that can be broken down into smaller, similar prob-
lems.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
Arguments: These are the actual values passed to the function when
it is called.
# function definition
def calculate_area(length, width):
"""
This function calculates the area of a rectangle.
"""
area = length * width
return area
greet("Alice")
greet("Bob", "Hi")
describe_pet(animal_type="dog", pet_name="Rex")
describe_pet(pet_name="Mittens", animal_type="cat")
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3))
print(sum_numbers(4, 5, 6, 7))
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
Variable Scopes
x = 10 # Global variable
def print_global():
print(x)
print_global()
def modify_global():
global x
x = 20
y = 10 # global variable
def print_local():
y = 5 # Local variable
z = 7 # Local variable
print(y,z)
print_local()
print(z) # This would cause an error
print(y) # prints the value 10
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 29 / 31
Dead Code
def example_function():
return "This will be returned"
print("This will never be printed") # Dead code
print(example_function())
Thank You!!!