0% found this document useful (0 votes)
4 views

CSC231_Lecture5_2025

The lecture covers functions and file handling in Python, emphasizing the definition, types, and syntax of functions, as well as their invocation and return values. It also discusses file operations, including opening, reading, writing, and closing files, along with the use of libraries for handling Excel files. Key concepts include local and global variables, the importance of parameters, and the use of lambda functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CSC231_Lecture5_2025

The lecture covers functions and file handling in Python, emphasizing the definition, types, and syntax of functions, as well as their invocation and return values. It also discusses file operations, including opening, reading, writing, and closing files, along with the use of libraries for handling Excel files. Key concepts include local and global variables, the importance of parameters, and the use of lambda functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

LECTURE 5

Sakpere A.B.
Department of Computer Science,
University of Ibadan.
Recap
Last week was all about:
Selection and Iteration Statements
if statements, if else, if elif, ternary operators, nested
if
while loop, for loop, nested loop
break, continue
Today’s Lecture:
Functions, File Handling
Function: Definition
Definition:
A block of reusable code that performs a specific task.
Key Benefits:
Increases code reusability.
Improves readability and organization.
Reduces redundancy.
Function
Functions are not run in a program until they
are “called” or “invoked” in a program
Function characteristics:
has a name
has parameters (0 or more)
has a docstring (optional but recommended)
has a body
returns value/output
Types of Function
Built-in Functions
Predefined in Python, e.g., print(), len(), type()
User-Defined Function
Created by the programmer to address specific needs.
Syntax
Syntax:
def function_name(parameters):
# Code block
return value

Components:
def: Keyword to define a function.
function_name: The name of the function.
parameters: Inputs to the function (optional).
Code block: Code to be executed
return: Outputs a result from the function (optional).
How to write a function(Example)
A simple function to print hello (takes no parameter and has
no return statement)
def print_hello():
print("Hello")
The body of a function is usually indented just after the
function name/header
Function do things,therefore you should always choose a
function name that expresses what it does
This simple example of a function will always do exactly the
same thing - to print “Hello”
A function has to be called or invoked before it can be
active: print_hello()
How to invoke a function
Defining a function doesn’t make it run
To run a function, we have to call it
To call them, we simply use its name followed by
round brackets and any parameters in between if
any
e.g. our simple example can be invoked by
print_hello()
inbuilt functions are invoked same ways as well e.g.
len(“Hello”), print(“hello), "hello".upper()
Function Call inside Another
Function
Key Points
A function can call:
Other user-defined functions.
Built-in functions.
The order of execution is based on the function call
hierarchy.
The inner function call executes first, and its result is
used in the outer function.
def greeting():
print_hello()
Quiz
Which keyword is used to define a function in
Python?
a) fun
b) define
c) def
d) func

The ________ function in Python is used to get


input from the user.
Quiz
What is the correct way to call a function
named my_function with no arguments?
a) call my_function
b) my_function
c) my_function()
d) invoke my_function()
Parameters in Function
Parameters are placeholders in a function
definition that accept values (known as
arguments) when the function is called.

Parameters enable functions to perform


dynamic and reusable operations.
Types of Parameters
Positional Parameters
Default Parameters
Keyword Parameters
Variable-length Parameters (to be covered
later)
1. Positional Parameters
Parameters that must be passed in the correct
order.
They are required unless default values are
provided.
Example:
def add(a, b):
return a + b
print(add(3, 5)) # Output: 8
Explanation: a and b must be provided in the
order defined in the function.
2. Default Parameters
Parameters with a default value, used if no argument is
provided.
Example:
def add(a = 1, b = 2):
return a + b
print(add(3, 5)) # Output: 8
print(add()) #Output:3
print(add(2)) #Output:4
Explanation: If a,b is not provided, the default value 1,2 is
used.
3. Keyword Parameters
Allows you to pass arguments using the
parameter names, regardless of order.
Example:
def add(a, b):
return a + b
add(b=6, a=7)
Explanation:
Keyword arguments allow flexibility in the order
of arguments.
Practical Use Case
def calculator(a, b, operation="add"):
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide" and b != 0:
return a / b
else:
return "Invalid operation or division by zero"
print(calculator(10, 5, operation="multiply")) # Output: 50
Further Examples: Calling a
function inside another
def square(num):
return num ** 2

def sum_of_squares(a, b):


return square(a) + square(b)

print(sum_of_squares(3, 4)) # Output: 25

Explanation:
The square function is called inside the
sum_of_squares function.
The sum_of_squares function computes
Chaining Function Calls
Functions can call each other in a chain for complex operations.
def add(a, b):
return a + b

def double(num):
return num * 2

def process_numbers(x, y):


return double(add(x, y))

print(process_numbers(3, 5))
Question: What will be the order of execution?
Quiz
What will be the output of the following code?

def add(a, b=5):


return a + b
print(add(3))
a) 8
b) 3
c) 5
d) None
Quiz
Which of the following is a correct example of a
function with a default parameter?

a) def greet():
b) def greet(name="Guest"):
c) def greet("Guest"):
d) None of the above
Quiz
What will be the output of the following code?

def example(x):
x=x+1
return x
print(example(5))
a) 6
b) 5
c) None
d) Error
return values
A function can return none, single value and
multiple values

The return value of a function can be stored in


a variable
No Return Value (None)
If a function does not have a return statement,
it returns None by default.
Example:
def no_return_function():
print("This function has no return value")

result = no_return_function()
print(result) # Output: None
Single Value Return
def square(num):
return num ** 2

answer = square(2)
Explanation:
return stores the result (num ** 2) into variable,
answer.
Single Value Return
def greet(name):
return f"Hello, {name}!"

print(greet("Aderonke")) # Output: Hello, Aderonke!

Explanation:
The greet function returns a string that can be
used elsewhere.
Multiple Values Return
def math_operations(a, b):
return a + b, a - b, a * b

sum_, diff, product = math_operations(10, 5)


print(sum_, diff, product) # Output: 15, 5, 50
Explanation:
Functions can return multiple values as a tuple.
These values can be unpacked and used separately.
Using Returned Values in Other
Functions
def add(a, b):
return a + b

def multiply_with_sum(a, b, factor):


return add(a, b) * factor

print(multiply_with_sum(2, 3, 4)) # Output: 20


Explanation:
The add function's return value is used in
multiply_with_sum.
Nested Returns
def calculate(a, b):
def add():
return a + b
def subtract():
return a - b
return add(), subtract()

print(calculate(10, 5)) # Output: (15, 5)

Explanation:
Inner functions add and subtract return
values to the outer function.
Calculating Areas and Perimeters

def rectangle_properties(length, width):


return length * width, 2 * (length + width)

area, perimeter = rectangle_properties(5, 3)


print(f"Area: {area}, Perimeter: {perimeter}")
# Output: Area: 15, Perimeter: 16
Quiz
What will be the output of this code?

def add(a, b):


return a + b
def double_sum(a, b):
return 2 * add(a, b)
print(double_sum(2, 3))
Quiz
What will be the output of the following code?
def outer_function():
x = 10
def inner_function():
return x + 5
return inner_function()

print(outer_function())
a) 15
b) 10
c) 5
d) 20
e) Error
Quiz
Which of the following is NOT true about return
in Python?

a) It can return multiple values.


b) It can return None.
c) It can terminate a function early.
d) It is mandatory in every function.
Quiz
What is the difference between return and print
in a function?
Variable Scope
Local Variables:
Declared inside a function; accessible only within the
function.
Global Variables:
Declared outside functions; accessible throughout the
program.
Global Variables
Defined outside all functions.
Accessible throughout the program.
Exists during the entire program execution.
Example:
y = 20 # Global variable
def example():
print(y)
Global Variable

y = 20 # Global variable

def my_function():
print("Value of y inside the function:", y)

my_function()
print("Value of y outside the function:", y)
Local Variables
Defined inside a function.
Accessible only within the function.
Exists only during the function execution.
Example:
def example():
x = 10 # Local variable
print(x)
Local Variable
def my_function():
x = 10 # Local variable
print("Value of x inside the function:", x)

my_function()
print(x) # This will raise an error because x is
not accessible outside the function
Using Global Variables Inside
Functions
If you modify a global variable inside a function, you must
declare it as global; otherwise, Python will treat it as a new
local variable.
z = 30 # Global variable

def my_function():
global z
z = 40 # Modifies the global variable
print("Value of z inside the function:", z)

my_function()
print("Value of z outside the function:", z)
Quiz
Compare recursion and iteration.
Lambdas

Definition: A small, anonymous function.


Purpose: Designed for short-term, throwaway use.
Simplifies code for small functions.
Syntax: lambda arguments: expression (lambda is a
keyword used to define anonymous function)
Single-line expressions.
No return statement needed (it’s implied).
Can take multiple arguments but only one
expression.
Lambdas
It should only be used for very simple functions
If its looking too complicated, write it out as a
full and regular function
Lambdas
Example 1: #Equivalent

a = lambda:3 def a():


return 3
Example 2:
b = lambda x,y: x+y def b(x,y):
return x+y
Quiz
Write the function definition equivalent of the
lambdas expression below:

square = lambda x: x ** 2
Key Takeaways
Functions can delegate tasks to other functions,
promoting code reuse.
Execution Order:
The inner function is executed first, and its
result is used by the calling function.
Flexibility:
Functions can combine built-in logic, user-
defined functions, and parameters to achieve
dynamic behavior.
File Handling
Definition:
It means reading, writing and and managing
files in a program
Its easy to work with files using built-in
functions
Why is File Handling Important?
Storing and retrieving data.
Logging application activities.
Processing large data sets.
File Types
Text Files (.txt): Stores human-readable
content like plain text.
Excel Files (.xls)
Binary Files: Stores data in binary format, like
images or compiled programs.
File Operations
Opening Files: open() function.
Reading Files: read(), readline(), readlines().
Writing Files: write(), writelines().
Closing Files: close() function.
Using with Statement: Automatic file closing.
File Modes
"r": Read mode (default).
"w": Write mode (overwrites the file).
"a": Append mode (adds to the file).
"x": Exclusive creation mode.
"r+": Read and write.
Reading Files
Methods for Reading:
read(): Reads the entire file as a string.
readline(): Reads one line at a time.
readlines(): Returns a list of all lines.

file = open("example.txt", "r")


content = file.read() # Read the content of the
file
print(content) # Print the actual content
file.close() # Always close the file
Opening and Closing Files
Opening a File:
file = open("example.txt", "r")

Closing a File:
file.close()
Alternative with with Statement:
Using the with statement is the recommended
approach as it automatically closes the file:

with open("example.txt", "r") as file:


content = file.read()
print(content)

with open("example.txt", "r") as file:


content = file.readline()
print(content)
Creating and Writing to a File
# Create a file and write some content to it
with open("new.txt", "w") as file:
file.write("Hello, this is a simple file writing
example in Python!")
print("File created and written
successfully!")
Explanation:
The "w" mode creates a new file or overwrites
an existing file.
The with statement ensures the file is closed
Writing Multiple Lines to a File
lines = ["Line 1: Python is great!", "Line 2: File
handling is simple!", "Line 3: Enjoy coding!"]

with open("multilines.txt", "w") as file:


file.writelines(line + "\n" for line in lines)
print("Multiple lines written successfully!")
Appending to a File
# Appending content to an existing file
with open("example.txt", "a") as file:
file.write("\nThis line is appended to the file.")
print("Content appended successfully!")
Explanation:
The "a" mode appends new content to the end
of the file without overwriting existing data.
Working with Excel Files
Python provides powerful libraries:
- openpyxl: Read/write Excel 2010+ files (.xlsx).
- pandas: Data manipulation and analysis with Excel
support.
- xlrd: Read older Excel files (.xls).
- xlsxwriter: Create .xlsx files with advanced formatting.
Install libraries using pip install openpyxl pandas xlsxwriter
xlrd
Common File Formats:
.xlsx (Excel 2007+)
.xls (Excel 97-2003)
.csv (Comma Separated Values)
Reading Excel Files
Load Excel files for data extraction.
Access specific cells, rows, or columns.
You need to import the needed library and function:
from openpyxl import load_workbook
Explanation:
openpyxl: This is a Python library used for working with
Excel files in the .xlsx format.
load_workbook: This is a function provided by the
openpyxl library. It is used to load an existing Excel
workbook (a .xlsx file) into your Python program for
reading or editing.
Further Example
from openpyxl import Workbook
# Create a new workbook
workbook = Workbook()
# Access the active sheet
sheet = workbook.active
# Add data to the sheet
sheet["A1"] = "Name"
sheet["B1"] = "Age"
sheet["A2"] = "Alice"
sheet["B2"] = 25
# Save the workbook
workbook.save("new_file.xlsx")
Creating a new excel file
from openpyxl import Workbook
# Create a new workbook
workbook = Workbook()

from openpyxl import Workbook: imports the


Workbook class from the openpyxl library. The
Workbook class is used to create a new Excel file
(workbook).

workbook = Workbook(). This creates a new workbook


object. A workbook is essentially a container for one or
more Excel sheets.
Creating a new excel file
from openpyxl import Workbook
# Create a new workbook
workbook = Workbook()
# Access the active sheet
sheet = workbook.active
# Add data to the sheet
sheet["A1"] = "Name"
sheet["B1"] = "Age"
sheet["A2"] = "Alice"
sheet["B2"] = 25
# Save the workbook
workbook.save("new_file.xlsx")
Writing into an excel sheet
from openpyxl import Workbook
# Create a new workbook and access the active sheet
workbook = Workbook()
sheet = workbook.active
#List of lists to write (each sub-list is a row)
data = [
["Name", "Age", "Country"],
["Alice", 25, "USA"],
["Bob", 30, "UK"],
["Charlie", 28, "Canada"]
]
# Write each sub-list as a row in the Excel sheet
for row in data:
sheet.append(row)
# Save the workbook to a file
workbook.save("list_of_lists_to_excel.xlsx")
print("Data written to Excel successfully!")
Looping Through Rows and
Columns
for row in sheet.iter_rows(min_row=1,
max_row=5, values_only=True):
print(row)
Exercise 1
Create a function called func_a, which prints a
message.
Call the function.
Assign the function object as a value to the
variable b, without calling the function.
Now call the function using the variable b.
Exercise 2
Create a function called hypotenuse, which
takes two numbers as parameters and prints
the square root of the sum of their squares.
Call this function with two floats.
Call this function with two integers.
Call this function with one integer and one float.
Exercise 3
Rewrite the hypotenuse function from exercise
2 such that it returns a value instead of printing
it.
Call the function with two numbers, and print
the result.
Exercise 4
Write a function to find the sum, average, minimum, and
maximum of a list of numbers.
Write a program to display only those numbers from a list
that satisfy the following conditions:
The number must be divisible by five
If the number is greater than 150, then skip it and move
to the next number
If the number is greater than 500, then stop the loop
Write a program that can multiply 2 numbers provided by
the user without using the * operator
Use a loop to display elements from a given list present at
odd index positions
Exercise 5
You are building a file storage system that
compresses text files using a simple string
compression algorithm (e.g., "aaabbbcc" →
"a3b3c2").
Questions:
Write a program to compress the content of
textfile.txt and save it as compressed.txt.
Extend the program to decompress
compressed.txt back into its original form and
verify the integrity of the data.
Exercise 6
You have two text files, file1.txt and file2.txt.
Both files contain student names but might
have some differences in the entries.
Questions:
Write a program to find and list names that are
present in file1.txt but not in file2.txt.
Extend the program to output the common
names into a new file named
common_names.txt?
Exercise 7
Write a program to:
Encrypt the content of a text file (plain.txt) and
save the encrypted content to a new file
(encrypted.txt).
Decrypt the encrypted file (encrypted.txt) back
to its original content.
Hints:
Use a simple encryption algorithm.
Exercise 8
Write a program to:
Search for a specific word (e.g., "Python") in
sample.txt.
Print all the lines containing the word along with
their line numbers.

Write a Python program to:


Read the content of sample.txt.
Count the number of lines and words in the file.

You might also like