CSC231_Lecture5_2025
CSC231_Lecture5_2025
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
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
print(process_numbers(3, 5))
Question: What will be the order of execution?
Quiz
What will be the output of the following code?
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
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}!"
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
Explanation:
Inner functions add and subtract return
values to the outer function.
Calculating Areas and Perimeters
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?
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
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.
Closing a File:
file.close()
Alternative with with Statement:
Using the with statement is the recommended
approach as it automatically closes the file: