0% found this document useful (0 votes)
7 views26 pages

Lecture4 Object Oriented Programming Python

The document provides an overview of Object Oriented Programming in Python, focusing on input and output operations, including functions for reading and writing files, as well as string formatting techniques. It covers various methods for console input and output, file handling, and structured data management using CSV and JSON formats. Additionally, it discusses advanced I/O techniques and file positioning in Python.

Uploaded by

sog.gregoy
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)
7 views26 pages

Lecture4 Object Oriented Programming Python

The document provides an overview of Object Oriented Programming in Python, focusing on input and output operations, including functions for reading and writing files, as well as string formatting techniques. It covers various methods for console input and output, file handling, and structured data management using CSV and JSON formats. Additionally, it discusses advanced I/O techniques and file positioning in Python.

Uploaded by

sog.gregoy
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

Object Oriented Programming(Python)

Emmanuel Ali(PhD)

March 29, 2026

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 1 / 26


Outline

1 Input and Output in Python

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 2 / 26


Input and Output in Python

Input and output (I/O) operations are essential for interacting with
users and handling data. Python provides simple, flexible functions for
basic I/O and powerful tools for handling various types of files and data
formats.

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 3 / 26


Console Input

Input The input() function allows you to take user input as a string.
name = input ( " Enter your name : " )
age = input ( " Enter your age : " )

This function always returns data as a string, so if you need another


type (like an integer), you’ll need to cast it.
age = int ( input ( " Enter your age : " ) ) # Converts input to an
integer

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 4 / 26


Console Output
print (* objects ,
Definition sep = ' ' ,
print() is a built-in Python function that end = '\ n ' ,
writes objects to the standard output stream file = sys . stdout ,
(stdout) — or to any text stream — followed by a flush = False )
newline.

>>> print ( " Hello , World ! "


Available in Python 3.x (was a statement in )
Python 2)
Hello , World !
Accepts zero or more positional arguments
Returns None >>> print () # blank
Used for debugging, logging, and user line
interaction # returns
None

. Python 2 vs Python 3

Python 2: print "Hello" (statement)


Python 3: print("Hello") (function)

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 5 / 26


Basic Syntax & Parameters

# Zero arguments Param Default Purpose


print () *objects — Zero or more values to
print
# One argument sep ’ ’ Inserted between ob-
jects
print ( " Python " )
end ’\n’ Appended after last
object
# Multiple arguments file [Link] Stream to write to
print ( " a " , " b " , " c " ) flush False Force immediate write

# Mixed types "x" "y" "z"


print ( " Sum : " , 3 + 4)
print ( True , 3.14 , None )
x , y , z \n
|{z} |{z} |{z}
print() calls str() on every argument before sep sep end
outputting — no manual type conversion
needed.

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 6 / 26


The sep Parameter — Customising Separators
Practical use cases for sep:
sep specifies the string inserted between CSV rows:
consecutive arguments. Default: a single space print(a,b,c, sep=",")
’ ’.
Path construction: print("usr",
"bin","python", sep="/")
# Default sep ( space )
Aligned columns:
print ( " a " , " b " , " c " ) print(h1,h2, sep="\t")
Concatenation:
# Comma - space separator
print("py","thon", sep="")
print ( " a " , " b " , " c " , sep = " , " )
name = " Alice "
# No separator age = 30
print ( " a " , " b " , " c " , sep = " " ) city = " Abuja "
# Newline separator print ( name , age , city , sep = "
print ( " one " , " two " , " three " , ," )
sep = " \ n " ) # Output : Alice ,30 , Abuja
# Custom separator sep must be a string. Passing a non-string
print (2024 , 12 , 25 , sep = " -" ) raises TypeError.

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 7 / 26


The end Parameter — Controlling Line Endings
Progress bar simulation:
end specifies what is appended after the last
argument. Default: newline ’\n’. import time

for i in range (1 , 6) :
# Default end (\ n ) print ( f " \ rProgress : { i
print ( " Hello " ) *20}% " ,
print ( " World " ) end = " " , flush = True
)
# Stay on same line time . sleep (0.4)
print ( " Hello " , end = " " ) print () # final newline
print ( " World " )
Printing a sequence inline:
# No newline at all
for i in range (1 , 6) :
print ( " A " , end = " " )
print (i , end = " " )
print ( " B " , end = " " )
# Output : 1 2 3 4 5
print ( " C " )
Use end="" combined with flush=True for
# Custom end real-time terminal output (e.g., progress
print ( " Loading " , end = " ... " ) indicators).
print ( " Done " )
# Loading
Emmanuel ... Done
Ali(PhD) 2nd Semester March 29, 2026 8 / 26
The file and flush Parameters
file — Redirecting Output flush — Forcing Immediate
Output
import sys
import time
# Print to stderr
print ( " Error ! " , file = sys . # Without flush may
stderr ) buffer
print ( " Step 1 done " , end = " "
# Print to a file object )
with open ( " log . txt " , " w " ) as f time . sleep (2)
: print ( " Step 2 done " )
print ( " Log entry 1 " , file =
f) # With flush immediate
print ( " Log entry 2 " , file = output
f) print ( " Step 1 done " ,
# Writes two lines to log . txt end = " " , flush = True )
time . sleep (2)
# Verify print ( " Step 2 done " , flush =
with open ( " log . txt " ) as f : True )
print ( f . read () )
flush=True
Emmanuel Ali(PhD) 2nd Semester
Output Buffer March 29, 2026 / File 9 / 26
Stream
String Formatting with print() — Overview
Style Since Best For
Three Main Approaches
% Python 2 Legacy code
1 %-formatting (old style, Python 2
legacy) .format() Python 3.0 Named pla
holders, reuse
2 [Link]() (Python 3, versatile)
f-strings Python 3.6 Readability,
3 f-strings (Python 3.6+, recommended)
pressions
Common format specifiers:

name = " Alice "


score = 95.75
x = 3.14159
n = 1234567
# % formatting
print ( " Name : %s , Score : %.1 f "
print ( f " { x :.2 f } " ) # 3.14
% ( name , score ) )
print ( f " { x :10.3 f } " ) #
3 .142
# str . format ()
print ( f " { n : ,} " ) #
print ( " Name : {} , Score : {:.1 f }
1 ,234 ,567
"
print ( f " { n :010 d } " ) #
. format ( name , score ) )
0001234567
print ( f " { x : e } "March
) # 10 / 26
# f Emmanuel
- stringAli(PhD)
( recommended ) 2nd Semester 29, 2026
[Link]() — Positional & Named Placeholders
"{placeholder}".format(value) 3. Format Specifiers {:spec}
Placeholders use {} with optional:
{index} · {name} · {index:format_spec} x = 3.14159; n = 1234567; s
= " hi "
1. Positional (auto & indexed)
print ( " {:.2 f } " . format ( x ) )
# Auto - numbered # 3.14
print ( " {} + {} = {} " . format print ( " {:10.3 f } " . format ( x ) )
(3 , 4 , 7) ) # 3 .142
# Explicit indices print ( " {: e } " . format ( x ) )
print ( " {0} and {1} , {0}! " . # 3.141590 e +00
format ( " Hi " ," you " ) ) print ( " {: ,} " . format ( n ) )
# Reuse / reorder # 1 ,234 ,567
print ( " {1} before {0} " . print ( " {:010 d } " . format ( n ) )
format ( " B " ," A " ) ) # 0001234567
print ( " {: >10} " . format ( s ) )
2. Named Placeholders # hi
print ( " {: <10} " . format ( s ) )
print ( " { name } scored { score } # hi
" . format ( print ( " {:^10} " . format ( s ) )
name = " Alice " , score # hi
=92) ) print ( " {:*^10} " . format ( s ) )
# Alice
Emmanuel scored
Ali(PhD) 92 2nd Semester March 29, 2026 11 / 26
f-Strings — Formatted String Literals (Python 3.6+)
x = 42
Syntax y = x ** 2
Prefix a string literal with f or F. Expressions print ( f " { x =} , { y =} " )
inside { } are evaluated at runtime.
# Useful during debugging :
# Variable substitution data = [1 , 2 , 3]
name = " Bob " print ( f " { len ( data ) =} " )
print ( f " Hello , { name }! " )
# Arithmetic expressions students = [
a, b = 7, 3 ( " Alice " , 92) , ( " Bob " ,
print ( f " { a }/{ b } = { a / b :.2 f } " ) 78) ,
# Function calls inside braces ( " Carol " , 88) ,
items = [4 , 2 , 7 , 1] ]
print ( f " Max : { max ( items ) } " ) print ( f " { ' Name ': <10} { ' Score
# Conditional expression ': >5} " )
x = -5 print ( " -" * 16)
print ( f " |{ x }| = { abs ( x ) } " ) for name , sc in students :
# Nested f - strings ( Py 3.12+) print ( f " { name : <10} { sc
width = 10 : >5} " )
print ( f " { ' center ':^{ width }} " ) # Name Score
Emmanuel Ali(PhD) # - - - - - - - - - - - -March
2nd Semester - - - -29, 2026 12 / 26
File Input and Output
Python offers built-in support for reading and writing files. Files can be opened
in various modes, such as read, write, and append.
Opening Files Use the open() function to open a file. The syntax is:
file = open ( " filename . txt " , mode )

Common modes:
’r’: Read (default).
’w’: Write (creates a new file or overwrites if it exists).
’a’: Append (writes data to the end of the file).
’b’: Binary mode (for binary files like images).
’r+’: Read and write.

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


file . write ( " Hello , World ! " )
file . close ()

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 13 / 26


File Input and Output
Reading Files
read(): Reads the entire file as a single string.
content = file . read ()

readline(): Reads one line at a time.


line = file . readline ()

readlines(): Reads all lines and returns a list of lines.


lines = file . readlines ()

Using with Statements Using with automatically closes the file after
the block, even if an error occurs.
with open ( " example . txt " , " r " ) as file :
content = file . read ()
print ( content )

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 14 / 26


File Input and Output

Writing to Files
write(): Writes a string to the file.
file . write ( " Hello , World !\ n " )

writelines(): Writes a list of strings to the file (without adding


newlines).
lines = [ " First line \ n " , " Second line \ n " ]
file . writelines ( lines )

Closing Files Always close files after reading or writing to free up


system resources.
file . close ()

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 15 / 26


Reading and Writing Structured Data

CSV Files Python’s csv module allows you to handle CSV (Comma
Separated Values) files easily.
Reading CSV
import csv
with open ( " data . csv " , " r " ) as csvfile :
reader = csv . reader ( csvfile )
for row in reader :
print ( row )

Writing CSV
with open ( " data . csv " , " w " , newline = " " ) as csvfile :
writer = csv . writer ( csvfile )
writer . writerow ([ " Name " , " Age " , " City " ])
writer . writerow ([ " Alice " , 30 , " New York " ])

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 16 / 26


Reading and Writing Structured Data

JSON Files JSON (JavaScript Object Notation) is a common data


format for APIs and data storage.
Writing JSON
import json
data = { " name " : " Alice " , " age " : 30}
with open ( " data . json " , " w " ) as jsonfile :
json . dump ( data , jsonfile )

Reading JSON
with open ( " data . json " , " r " ) as jsonfile :
data = json . load ( jsonfile )

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 17 / 26


File Positioning

tell(): Returns current position in the file.


seek(offset, whence): Moves the position.
file . seek (0) # Go to the start of the file
position = file . tell () # Current position

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 18 / 26


Working with Binary Files

Open with 'rb' or 'wb' for binary mode.


with open ( " image . jpg " , " rb " ) as binary_file :
data = binary_file . read () # Reads binary data

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 19 / 26


Other Advanced I/O Techniques

Standard Input and Output Redirection Python’s sys module


allows redirection of standard input, output, and error.
import sys
sys . stdout = open ( " output . txt " , " w " ) # Redirects print
output to a file
print ( " This will be written to the file . " )
sys . stdout . close ()

Working with Paths The pathlib module provides an object-oriented


approach for file paths.
from pathlib import Path
path = Path ( " example . txt " )
if path . exists () :
print ( " File exists . " )

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 20 / 26


Exercise

Password Validation
Prompt the user to enter a password and check if it meets certain
criteria (e.g., at least 8 characters long, contains at least one digit, one
uppercase letter, and one lowercase letter).

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 21 / 26


Exercise
Student Grade Book
Create a program that allows the user to enter student names and their scores until they type
’done’. Then, display a formatted grade report on screen and save it to a text file.

Instructions
Initialize Storage:
Start with two empty lists — one for student names and one for their corresponding scores.
Loop for User Input:
Use a while loop to repeatedly prompt the user for a student name.
If the user types ’done’, exit the loop.
Otherwise, prompt for the student’s numeric score and store both in their respective lists.
Compute and Display the Report:
After exiting the loop, calculate the class average.
Print a numbered table showing each student’s name, score, and letter grade (A ≥ 70, B ≥ 60,
C ≥ 50, F otherwise).
Highlight the highest and lowest scores.
Save to File:
Write the full grade report to grade_book.txt, with each student on a new line, followed by a
summary line showing the class average.

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 22 / 26


Exercise
Personal Expense Tracker
Create a program that lets the user log expense entries (category and amount) until they
type ’done’. Summarise spending by category on screen and append the session log to a file.
Instructions
Initialize Storage:
Start with an empty dictionary to map each spending category to its running total, and an
empty list to keep a timestamped log of every entry.
Loop for User Input:
Use a while loop to prompt the user for an expense category (e.g. Food, Transport).
If the user types ’done’, exit the loop.
Otherwise, prompt for the amount, validate that it is a positive number, and update both the
dictionary total and the log list.
Display the Summary:
After exiting the loop, print each category and its total in a formatted two-column table
(category left-aligned, amount right-aligned to two decimal places).
Print the grand total at the bottom and identify the category with the highest spending.
Save to File:
Open [Link] in append mode and write the session log line by line, with each entry
formatted as:
Category | Amount | Running Total

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 23 / 26


Exercise

Shopping List
Create a program that allows the user to enter items into a shopping list
until they type ’done’. Then, print the final list and sends to a text file.
Instructions
Initialize an Empty List:
Start with an empty list to store each item the user adds to the
shopping list.
Loop for User Input:
Use a while loop to prompt the user to enter items one by one. If the
user types ’done’, exit the loop. Otherwise, add each item to the list.
Print and Save the List:
After exiting the loop, print each item in the list with numbering. Write
the entire list to a text file, with each item on a new line.

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 24 / 26


Simple Voting System
Create a program that allows users to vote for their favorite fruit from a predefined list.
Count the votes and display the results.
Instructions
1. Define the List of Fruits: Start by creating a predefined list of fruits for users to choose
from. This list will restrict the choices, so users can only vote for items on this list.
2. Initialize a Vote Counter:
Use a dictionary to store each fruit as a key and initialize the value of each key to 0. This
value will represent the vote count for each fruit.
3. Prompt for Voting:
Display a message to the user listing all available fruits they can vote for. Mention that they
can type ‘’done’‘ to finish voting.
4. Create a Loop to Record Votes:
Use a while loop to continuously ask for user input until the user types ’done’.
- Inside the loop:
- Prompt the user to enter a vote by typing the name of a fruit.
- Convert the input to lowercase to ensure the voting process is case-insensitive.
- Check if the entered fruit is in the predefined list:
- If it is, increment the corresponding count in the ‘votes‘ dictionary.
- If it’s not a valid choice, display an error message and ask the user to try again.
5. Display the Final Results:
- After the loop ends (when the user types ’done’), display the results by iterating over the
‘votes‘ dictionary.
- Print each fruit with its corresponding vote count.
- Capitalize each fruit name in the output for readability.

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 25 / 26


Exercise

Recipe Card
Write a program that asks the user for ingredients and quantities for a
recipe, then prints a nicely formatted recipe card.
Initialize an Empty List for the Recipe:
Use a list to store ingredients and their quantities as tuples. Each tuple
will contain two elements: the ingredient name and the quantity.
Prompt for Ingredient and Quantity:
Use a loop to repeatedly ask the user to enter an ingredient and its
quantity. After each ingredient and quantity pair is entered, store it as a
tuple in the list. Allow the user to type ’done’ when they’re finished
adding ingredients.
Print the Recipe Card:
After the user finishes entering ingredients, print the recipe card with a
heading ("Recipe Card") and each ingredient with its quantity. Format
the output nicely, displaying each ingredient and quantity on a new line.

Emmanuel Ali(PhD) 2nd Semester March 29, 2026 26 / 26

You might also like