Computer Programming
Functions
Eyob S.
SITE, AAiT
June 16, 2024
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 1 / 31
Table of Contents
1 Introduction
2 Types of Functions
3 Parameters and Arguments
4 Variable Scopes
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 2 / 31
Introduction
Introduction
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 3 / 31
Definition
A function in Python is a block of reusable code designed to perform
a specific task.
It can take inputs, process them, and return a result.
Functions help in organizing code into manageable sections, making it
easier to understand, test, and maintain.
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 4 / 31
Why Functions?
Modularity: Functions allow the code to be divided into smaller,
manageable pieces.
Reusability: Functions can be called multiple times, avoiding code
duplication.
Maintainability: Functions simplify debugging and testing.
Abstraction: Functions hide implementation details and expose only
necessary parts to the user.
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 5 / 31
Defining and Calling Functions
Defining a Function:
def function_name(parameters):
"""
Docstring (optional)
"""
# Function body
return result
Calling a Function:
result = function_name(arguments)
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 6 / 31
Types of Functions
Types of Functions
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 7 / 31
1. Built-in Functions
Python provides many built-in functions that are always available. Here are
some of the most commonly used:
abs() divmod() input() open()
all() enumerate() int() ord()
any() eval() iter() pow()
bin() exec() print() float()
list() chr() len() range()
max() set() complex() round()
min() ord() sorted() next()
dict() hex() dir() type()
id() oct() str() sum()
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 8 / 31
Module
A module in Python is a file containing Python code (functions, classes,
variables) that can be imported and used in other Python programs.
Modules help organize and reuse code.
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 9 / 31
Important Modules in Python
Python’s standard library includes many modules that provide addi-
tional functionality. Here are some important ones:
math random
sys re
itertools functools
os collections
datetime json
heapq operator
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 10 / 31
Using the math Module
The math module provides mathematical functions and constants.
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793
print(math.factorial(5)) # Output: 120
print(math.sin(math.pi/2)) # Output: 1.0
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 11 / 31
Using the random Module
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))
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 12 / 31
Using the datetime Module
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
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 13 / 31
Using the os Module
The os module provides functions for interacting with the operating system.
import os
print(os.name) # Output: Name of the operating system
print(os.getcwd()) # Output: Current working directory
os.mkdir('new_folder') # Create a new directory
os.rmdir('new_folder') # Remove a directory
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 14 / 31
2. User-defined Functions
User-defined Functions: These are functions created by the user using
the def keyword.
def greet(name):
return f"Hello, {name}!"
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 15 / 31
3. Void Functions
Functions that do not have the return statement.
Used for performing actions or procedures.
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())
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 16 / 31
4. Fruitful Functions
Functions that return a value.
Used for calculations or data processing.
Example: Calculating the sum of two numbers.
def add(a, b):
return a + b
result = add(3, 5)
print(result)
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 17 / 31
5. Boolean Functions
Functions that return a boolean value (True/False).
Used for decision making.
Example: Checking if a number is even.
def is_even(n):
return n % 2 == 0
print(is_even(4))
print(is_even(7))
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 18 / 31
6. Recursive Functions
Functions that call themselves.
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))
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 19 / 31
Parameters and Arguments
Parameters and Arguments
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 20 / 31
Parameters and Arguments
Parameters: These are variables listed inside the parentheses in the
function definition.
def greet(name): # 'name' is a parameter
return f"Hello, {name}!"
Arguments: These are the actual values passed to the function when
it is called.
greet('Alice') # 'Alice' is an argument
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 21 / 31
Example
# function definition
def calculate_area(length, width):
"""
This function calculates the area of a rectangle.
"""
area = length * width
return area
# Function call with arguments
area = calculate_area(5, 3)
print(f"The area is {area}")
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 22 / 31
Default Parameters
Parameters with default values.
Used when some arguments are optional.
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice")
greet("Bob", "Hi")
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 23 / 31
Keyword Arguments
Parameters passed by name.
Increases readability and allows parameter reordering.
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet(animal_type="dog", pet_name="Rex")
describe_pet(pet_name="Mittens", animal_type="cat")
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 24 / 31
Unknown Number of Parameters
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}")
print_info(name="Alice", age=30, city="New York")
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 25 / 31
Variable Scopes
Variable Scopes
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 26 / 31
Global Variables
Variables defined outside any function.
Accessible from any part of the code.
x = 10 # Global variable
def print_global():
print(x)
print_global()
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 27 / 31
Global Variables
# Define a global variable
x = 10
def modify_global():
global x
x = 20
print("Before function call:", x)
modify_global()
print("After function call:", x)
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 28 / 31
Local Variables
Variables defined inside a function and only accessible within the
function.
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
Code that is never executed.
Can occur due to conditions that are always false.
Example: Unreachable code after a return statement.
Reduces code readability and can lead to maintenance issues.
def example_function():
return "This will be returned"
print("This will never be printed") # Dead code
print(example_function())
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 30 / 31
END
Thank You!!!
Eyob S. (SITE, AAiT) Computer Programming June 16, 2024 31 / 31