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

GE3151 PS and Python Programming - UNIT V

The document covers file handling in Python, including file systems, file types, and methods for reading and writing files. It details various file opening modes, attributes of file objects, and methods associated with file handling, along with illustrative examples. Additionally, it explains how to handle exceptions and provides examples of programs related to file operations.

Uploaded by

sudhar170683
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)
24 views

GE3151 PS and Python Programming - UNIT V

The document covers file handling in Python, including file systems, file types, and methods for reading and writing files. It details various file opening modes, attributes of file objects, and methods associated with file handling, along with illustrative examples. Additionally, it explains how to handle exceptions and provides examples of programs related to file operations.

Uploaded by

sudhar170683
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/ 28

PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science

UNIT V FILES, MODULES, PACKAGES


Files And Exceptions: Text Files, Reading and Writing Files, Format Operator; Command Line Arguments,
Errors and Exceptions, Handling Exceptions, Modules, Packages; Illustrative Programs: Word Count, Copy
File, Voter’s Age Validation, Marks Range Validation (0-100)

1. PYTHON FILE HANDLING


1.1 Basics of File Systems
A file system is a method used by operating systems to organize, store, retrieve, and manage data on storage
devices.
a. Key Functions of a File System
• Organization of Data: Files are stored in directories (or folders) to keep them organized.
• Storage Management: Determines how data is stored, retrieved, and written to the disk.
• Access Control: Manages permissions to ensure data security.
• File Management: Tracks the location and structure of files.

b. Components of a File System


1. Files: Basic units of storage containing data, e.g., text documents, images, or videos.
2. Directories/Folders: Containers for organizing files and other directories (subdirectories).
3. Metadata: Information about files, such as name, size, type, creation date, and permissions.
4. Partitions: Logical divisions of a storage device, each with its own file system.

c. File System Structure


• Tree Structure: Organizes files and directories hierarchically.
o Root Directory (/ in Linux, C:\ in Windows) is the starting point.
o Subdirectories branch out from the root.

Figure 1: Structure of File System


1.2 File
A file is a basic unit of storage used to save data on a computer. It is a collection of related information, such
as text, images, videos, or software, that is stored together and identified by a unique name.
a. Key Characteristics of a File
• Name: A file is identified by a name, typically including a file extension (e.g., document.txt or
photo.jpg).
• Data: Files contain the actual content, which could be text, numbers, images, audio, video, or other
types of information.
• Location: Stored in a specific directory or folder within a file system.
• Attributes: Files have metadata, such as size, creation date, last modified date, and permissions.

GE3151 Problem Solving and Python Programming 1


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
b. File Types
Files can be categorized into different types based on their content and purpose:
• Text Files: Contain plain or formatted text (e.g., .txt, .docx, .html).
• Binary Files: Store data in binary format, often used by software (e.g., .exe, .bin).
• Image Files: Contain graphical data (e.g., .jpg, .png, .gif).
• Audio Files: Store sound data (e.g., .mp3, .wav).
• Video Files: Contain moving picture data (e.g., .mp4, .mkv).
• Executable Files: Contain instructions for the computer to perform specific tasks (e.g., .exe, .sh).

1.3 Ways to Access Files


Accessing files involves opening or retrieving them from a storage location using various methods. The
following are the common methods used for accessing files: Sequential Access, Direct/Random Access, and
Indexed Sequential Access.

Indexed Sequential
Feature Sequential Access Direct/Random Access
Access
Access Data is accessed in a linear Data can be accessed directly Combination of sequential
Pattern order. at any position. and direct access.
Typically used in tape Used in devices like HDDs, Typically used in
Storage Type
drives or sequential files. SSDs, and RAM. databases or file systems.
Balanced, fast for both
Efficiency Slower for random access. Fast for direct/random access. sequential and random
access.
Reading log files, Retrieving elements from an Database search using an
Example
streaming data. array or database by key. index.
Faster than sequential, but
Performance Slower for random access. Fast access to any data. slower than pure random
access.

2. FILES IN PYTHON
2.1 File Opening Modes
Python’s open() function supports various modes for opening files:

<FileVariableName> = open(“filepath”, <mode>) or


<FileVariableName> = open(“filepath)

Mode Description
'r' Opens the file for reading only (default). File must exist. File pointer starts at the beginning.
'r+' Opens the file for reading and writing. File must exist. Pointer starts at the beginning.
'w' Opens the file for writing only. Creates the file if it doesn’t exist; overwrites if it does.
'w+'
Opens the file for reading and writing. Creates the file if it doesn’t exist; overwrites if it does.
Pointer starts at the beginning.
'a' Opens the file for appending. Creates the file if it doesn’t exist. Pointer starts at the end.
'a+'
Opens the file for reading and appending. Creates the file if it doesn’t exist. Pointer starts at the
end.

GE3151 Problem Solving and Python Programming 2


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
2.2 Attributes of File Object
An attribute of a file object is a property or characteristic associated with the file object that provides specific
information or capabilities related to the file. These attributes can be accessed directly using the dot notation
(e.g., file.name, file.mode) and describe properties such as the file's name, mode, encoding, or state
(open/closed). The following table lists out all the attributes of file object,

Attribute Description
file.name Returns the name of the file.
file.mode Returns the mode in which the file was opened ('r', 'w', 'a', etc.).
file.closed Returns True if the file is closed, False otherwise.
file.newlines Returns the newline convention used in the file (None, \n, \r\n, or a tuple of these).
file.seekable() Returns True if the file supports random access using seek().
file.readable() Returns True if the file can be read from.
file.writable() Returns True if the file can be written to.
file.fileno() Returns the file descriptor (integer) used by the underlying OS.

Example
# Open the file manually
file = open("example.txt", "w+")

# Write some content to the file


file.write("Hello, this is a test file.\nAnother line here.")

# Move the file pointer to the start for reading


file.seek(0)

# Display file object attributes


print("File Name:", file.name) # Name of the file
print("File Mode:", file.mode) # Mode in which the file was opened
print("Is File Closed?", file.closed) # Check if the file is closed
print("Newlines Used:", file.newlines) # Newline convention used in the file
print("Is File Seekable?", file.seekable()) # Can the file pointer be moved?
print("Is File Readable?", file.readable()) # Can the file be read?
print("Is File Writable?", file.writable()) # Can the file be written to?
print("File Descriptor (OS Level):", file.fileno()) # File descriptor used by the OS

# Ensure the file is closed to release resources


file.close()

# Check the closed status after explicitly closing the file


print("Is File Closed After Closing?", file.closed)

Output
File Name: example.txt
File Mode: w+
Is File Closed? False
Newlines Used: None
Is File Seekable? True
Is File Readable? True
Is File Writable? True
File Descriptor (OS Level): 3
Is File Closed After Closing? True

GE3151 Problem Solving and Python Programming 3


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
2.3 Methods in File Object
A text file is a file that contains printable characters and whitespace, organized into lines separated by
newline characters. The following table lists the various methods available for a file object in Python. The
syntax to invoke these methods is:
<FileVariableName>.<MethodName> (<arguments)

The following are the methods of file object:


Category Name Type Description
file.read(size=- Reads up to size characters/bytes. Reads all if
1) Method
size is omitted or -1.
Reading file.readline(siz Reads one line of text. If size is specified, reads
e=-1) Method
Methods up to size characters.
file.readlines(hi Reads all lines and returns them as a list. hint
nt=-1) Method
specifies the maximum number of bytes to read.
file.write(string Writes a string to the file. Returns the number of
) Method
Writing characters written.
Methods file.writelines(l Writes a list of strings to the file without adding
ist) Method
newlines automatically.
file.tell() Method Returns the current position of the file pointer.
Pointer
file.seek(offset,
Methods whence=0) Method Moves the file pointer to the specified position.
file.close() Method Closes the file and frees system resources.
Management file.flush() Method Forces the writing of buffered data to the file.
Methods file.fileno()
Returns the file descriptor used by the operating
Method
system.
file.readinto(buf
Binary-Specific fer) Method Reads bytes directly into a buffer object.
file.readable() Method Returns True if the file can be read from.
Query Methods file.writable() Method Returns True if the file can be written to.
file.seekable() Method Returns True if the file supports random access.

Example
# Open a file for demonstration
file = open("example.txt", "w+")

# Demonstrate file.write(string) and file.writelines(list)


file.write("Hello, World!\nThis is a test file.\n")
file.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])

# Flush the buffer to ensure data is written to the file


file.flush()

# Reset the file pointer to the beginning


file.seek(0)

# Demonstrate file.read(size=-1)
print("\nRead entire file content:")
print(file.read()) # Read the entire file

# Reset the file pointer again


file.seek(0)

GE3151 Problem Solving and Python Programming 4


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# Demonstrate file.readline(size=-1)
print("\nRead the first line:")
print(file.readline()) # Read the first line

# Demonstrate file.readlines(hint=-1)
file.seek(0)
print("\nRead all lines as a list:")
print(file.readlines()) # Read all lines and return as a list

# Demonstrate file.tell() and file.seek(offset, whence=0)


file.seek(10)
print("\nFile pointer position after seeking 10 bytes:", file.tell()) # Get current
position

# Demonstrate file.readable(), file.writable(), and file.seekable()


print("\nFile readable?", file.readable()) # Check if the file is readable
print("File writable?", file.writable()) # Check if the file is writable
print("File seekable?", file.seekable()) # Check if the file supports random
access

# Demonstrate file.fileno()
print("\nFile descriptor (OS level):", file.fileno())

# Demonstrate file.readinto(buffer)
file.seek(0) # Reset file pointer
buffer = bytearray(10) # Create a buffer of size 10
file.readinto(buffer) # Read bytes directly into the buffer
print("\nBuffer after reading into it:", buffer.decode())

# Close the file


file.close()
print("\nIs file closed?", file.closed)

Expected Output
Read entire file content:
Hello, World!
This is a test file.
Line 1
Line 2
Line 3

Read the first line:


Hello, World!

Read all lines as a list:


['Hello, World!\n', 'This is a test file.\n', 'Line 1\n', 'Line 2\n', 'Line 3\n']

File pointer position after seeking 10 bytes: 10

File readable? True


File writable? True
File seekable? True

File descriptor (OS level): 3

Buffer after reading into it: Hello, Worl

Is file closed? True

GE3151 Problem Solving and Python Programming 5


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
2.4 Reading Files
The text files can be read in four different ways as listed below:
• Using Read Method
• Using Readlines Method
• Using For Line In File Methods
• Using Readline Method

Method Description Best Use Case


read()
Reads the entire file as a single For small files where you need all content at
string. once.
readlines()
Reads all lines and returns them as For small-to-medium files where you need
a list. lines as a list.
for line in Iterates over the file object line by For large files to process one line at a time
file line. efficiently.
readline()
For scenarios where only specific lines are
Reads a single line from the file.
needed.

Example
# Create a sample file for demonstration
file = open("sample.txt", "w")
file.write("Hello, World!\n")
file.write("This is a test file.\n")
file.write("Python makes file handling easy.\n")
file.write("Have a great day!\n")
file.close()

# 1. Using read() method


file = open("sample.txt", "r")
print("Using read():\n")
print(file.read()) # Read the entire file content
file.close()

# 2. Using readlines() method


file = open("sample.txt", "r")
print("\nUsing readlines():\n")
lines = file.readlines() # Read all lines into a list
print(lines)
file.close()

# 3. Using for line in file


file = open("sample.txt", "r")
print("\nUsing for line in file:\n")
for line in file:
print(line.strip()) # Print each line without newline characters
file.close()

# 4. Using readline() method


file = open("sample.txt", "r")
print("\nUsing readline():\n")
print(file.readline().strip()) # Read and print the first line
print(file.readline().strip()) # Read and print the second line
file.close()

Output
Using read():

GE3151 Problem Solving and Python Programming 6


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Hello, World!
This is a test file.
Python makes file handling easy.
Have a great day!

Using readlines():
['Hello, World!\n', 'This is a test file.\n', 'Python makes file handling easy.\n',
'Have a great day!\n']

Using for line in file:


Hello, World!
This is a test file.
Python makes file handling easy.
Have a great day!

Using readline():
Hello, World!
This is a test file.

2.5 Opening Files in Different Modes.


# Demonstrating different file modes
# First, we create a sample file for demonstration
filename = "sample_modes.txt"

# 'w' mode: Open for writing (creates a new file or overwrites if it exists)
file = open(filename, 'w')
file.write("This is the first line in the file.\n")
file.write("This is the second line in the file.\n")
file.close()

# 'r' mode: Open for reading (file must exist)


print("Opening in 'r' mode:")
file = open(filename, 'r')
print(file.read()) # Reads the entire content of the file
file.close()

# 'r+' mode: Open for both reading and writing (file must exist)
print("\nOpening in 'r+' mode:")
file = open(filename, 'r+')
print("Original file content:", file.read()) # Reads the entire file
file.write("This is a new line added using r+ mode.\n") # Overwrites data at current
file position
file.close()

# 'w' mode: Open for writing (creates a new file or overwrites if it exists)
print("\nOpening in 'w' mode:")
file = open(filename, 'w')
file.write("This file is overwritten using 'w' mode.\n")
file.close()

# 'w+' mode: Open for reading and writing (creates a new file or overwrites if it
exists)
print("\nOpening in 'w+' mode:")
file = open(filename, 'w+')
file.write("This file is overwritten using 'w+' mode.\n")
file.seek(0) # Move pointer to the beginning of the file to read
print(file.read()) # Reads the content after writing
file.close()

GE3151 Problem Solving and Python Programming 7


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# 'a' mode: Open for appending (creates a new file if it doesn't exist, appends to file
if it does)
print("\nOpening in 'a' mode:")
file = open(filename, 'a')
file.write("This line is appended using 'a' mode.\n")
file.close()

# 'a+' mode: Open for reading and appending (creates a new file if it doesn't exist)
print("\nOpening in 'a+' mode:")
file = open(filename, 'a+')
file.write("This line is appended using 'a+' mode.\n")
file.seek(0) # Move pointer to the beginning of the file to read
print(file.read()) # Reads the entire content of the file
file.close()

Program Explanation of File Modes Used


1. 'r' (Read Mode)
• Opens the file for reading.
• The file must exist; otherwise, it raises a FileNotFoundError.
• It does not allow writing.

2. 'r+' (Read/Write Mode)


• Opens the file for both reading and writing.
• The file must exist; if it doesn't, it raises a FileNotFoundError.
• Writing starts from the current file pointer position (usually the start).

3. 'w' (Write Mode)


• Opens the file for writing.
• If the file already exists, it truncates the file (i.e., deletes the content and writes new data).
• If the file doesn’t exist, it creates a new one.

4. 'w+' (Read/Write Mode)


• Opens the file for both reading and writing.
• Like 'w', it creates a new file if it doesn’t exist, or truncates it if it does.
• You can both read and write to the file.

5. 'a' (Append Mode)


• Opens the file for appending.
• If the file doesn’t exist, it creates a new one.
• Data is written at the end of the file without altering existing content.

6. 'a+' (Read/Append Mode)


• Opens the file for both reading and appending.
• Like 'a', it creates a new file if it doesn’t exist.
• You can read the file and append new data at the end without modifying the existing content.

Expected Output
Opening in 'r' mode:
This is the first line in the file.
This is the second line in the file.

GE3151 Problem Solving and Python Programming 8


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Opening in 'r+' mode:
Original file content: This is the first line in the file.
This is the second line in the file.
This is a new line added using r+ mode.

Opening in 'w' mode:

Opening in 'w+' mode:


This file is overwritten using 'w+' mode.

Opening in 'a' mode:

Opening in 'a+' mode:


This file is overwritten using 'w+' mode.
This line is appended using 'a' mode.
This line is appended using 'a+' mode.

3. FORMAT OPERATOR
The format operator (%) in Python is a way to format strings and insert values into a string, similar to how
it works in the C programming language. It allows you to embed variables into strings, creating dynamic and
readable output. The format operator can be used with placeholders in a string to insert values at specific
locations.

Basic Syntax:
<format expression> % (v1, v2, v3 …. vn ) or
<format expression> % values

Where v1 to vn are variables that are formateed using the expression, values is a tuple with exactly the
number of items specified by the format string, or a single mapping object.

The syntax of format expressions is:


[key][flags][width][.precision][length type] conversion type

All the parameters other than conversion type are optional. It has to be specified only when needed.

• key: Specifies the field name in the format string. If not provided, it uses the positional argument.
• flags: Adjusts the formatting of the output (e.g., +, -, 0).
• width: Specifies the minimum number of characters for the output.
• .precision: Sets the number of decimal places for numbers.
• length type: Specifies the size or data type of the argument (e.g., h, l).
• conversion type: Specifies the type of formatting to apply (s, d, f, e, etc.).
Allthe parameters, except for the conversion type, are optional. You can include them in the format
expression only when needed.

3.1 Flags in Format Expression


Flag Description Example Output
+
Forces the sign to be displayed. Displays + for positive numbers +42
{:+d} with 42
and - for negative numbers.
- Left-aligns the value within the specified width. {:10d}with 42 42

0
Pads the value with zeros (0) instead of spaces to fill the specified {:010d} with 0000000042
width. 42

GE3151 Problem Solving and Python Programming 9


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Adds a leading space before positive numbers, similar to + but 42
{: d} with 42
uses a space instead of a +.
#
Alternate formatting. For numeric types, it adds a prefix like 0x 0xff
{:#x} with 255
for hexadecimal or 0o for octal.
, {:,} with 1,000,000
Adds a comma as a thousands separator. Only works for numbers. 1000000
_ {:_>10d} with ______42
Replaces padding spaces with underscores (_). 42

3.2 Conversion Types in Format Expression


In Python, conversion types are used in format expressions to specify how the value should be converted
and displayed. These conversion types control the format of numbers, strings, and other types, and they
determine how the final output will be displayed. The conversion type comes after the : in the format
expression and is an essential part of the formatting process. Conversion types are used in conjunction with
width, precision, and flags to format the output. The following table shows the list of common types in Python
format expressions.

Conversion
Description Example Output
Type
s Converts the value to a string. "{:s}".format(42) 42
d Converts the value to an integer (base 10). "{:d}".format(42) 42

i
Converts the value to an integer (base 10), "{:i}".format(42) 42
same as d.
f
Converts the value to a floating-point "{:f}".format(3.14159) 3.141590
number.
e
Converts the value to scientific notation "{:e}".format(1000000) 1.000000e+06
(exponential form).
E
Similar to e, but uses uppercase E for the "{:E}".format(1000000) 1.000000E+06
exponent.
g
Uses the most compact representation "{:g}".format(0.0000123) 1.23e-05
between f and e.
G
Similar to g, but uses uppercase E for the "{:G}".format(0.0000123) 1.23E-05
exponent.
x
Converts an integer to a lowercase "{:x}".format(255) ff
hexadecimal.
X
Converts an integer to an uppercase "{:X}".format(255) FF
hexadecimal.
o Converts an integer to an octal number. "{:o}".format(8) 10
b Converts an integer to a binary number. "{:b}".format(5) 101

c
Converts an integer to the corresponding "{:c}".format(97) a
Unicode character.
%
Converts the value to a percentage "{:%}".format(0.25) 25.000000%
(multiplies by 100 and adds %).

3.3 Example for Formatting Strings


# Demonstrating string formatting in Python with shortened variable names
# Shortened variables
n = "Alice"
a = 30

GE3151 Problem Solving and Python Programming 10


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
h = 5.6

# Using % operator (old-style formatting)


f_str_percent = "Name: %s, Age: %d, Height: %.1f" % (n, a, h)

# Using str.format() method (modern formatting)


f_str_format = "Name: {}, Age: {}, Height: {:.1f}".format(n, a, h)

# Using positional and keyword arguments with str.format()


f_str_pos = "Name: {0}, Age: {1}, Height: {2}".format(n, a, h)
f_str_kw = "Name: {n}, Age: {a}, Height: {h}".format(n=n, a=a, h=h)

# Using f-strings (formatted string literals)


f_str_fstring = f"Name: {n}, Age: {a}, Height: {h:.1f}"

# Showing formatted numbers


num = 1234.56789
f_num = f"Formatted number: {num:.2f}"
f_num_zeros = f"Formatted number with leading zeros: {num:010.2f}"

# Print all formatted strings


print(f_str_percent)
print(f_str_format)
print(f_str_pos)
print(f_str_kw)
print(f_str_fstring)
print(f_num)
print(f_num_zeros)

Output:
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Formatted number: 1234.57
Formatted number with leading zeros: 00001234.57

3.4 Example for Formatting Numbers


# Example program for formatting numbers

# Number for formatting


num = 1234.56789

# 1. Using % operator (old-style formatting)


percent_format = "Formatted number (%.2f): %.2f" % num
print(percent_format)

# 2. Using str.format() method (modern formatting)


format_method = "Formatted number ({:.2f}): {:.2f}".format(num, num)
print(format_method)

# 3. Using f-strings (formatted string literals)


f_string_format = f"Formatted number (f-string, .2f): {num:.2f}"
print(f_string_format)

# 4. Formatting with leading zeros


leading_zeros = f"Formatted number with leading zeros (010.2f): {num:010.2f}"
print(leading_zeros)

GE3151 Problem Solving and Python Programming 11


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# 5. Formatting with comma as thousands separator
thousands_separator = f"Formatted number with thousands separator: {num:,.2f}"
print(thousands_separator)

# 6. Formatting for percentage


percentage_format = f"Formatted as percentage: {num:.2%}"
print(percentage_format)

# 7. Rounding to an integer
rounded_number = f"Rounded to integer: {num:.0f}"
print(rounded_number)

Output:
Formatted number (%.2f): 1234.57
Formatted number ({:.2f}): 1234.57
Formatted number (f-string, .2f): 1234.57
Formatted number with leading zeros (010.2f): 00001234.57
Formatted number with thousands separator: 1,234.57
Formatted as percentage: 123457.89%
Rounded to integer: 1235

3.5 Example for Formatting Using Place Holders


# Formatting numbers and strings using placeholders

# Variables
name = "Alice"
age = 30
height = 5.6

# 1. Using the `%` operator (old-style formatting) for strings and numbers
formatted_str_percent = "Name: %s, Age: %d, Height: %.1f" % (name, age, height)
print(formatted_str_percent)

# 2. Using `str.format()` method (modern formatting) for strings and numbers


formatted_str_format = "Name: {}, Age: {}, Height: {:.1f}".format(name, age, height)
print(formatted_str_format)

# 3. Using positional placeholders with `str.format()`


formatted_str_pos = "Name: {0}, Age: {1}, Height: {2}".format(name, age, height)
print(formatted_str_pos)

# 4. Using keyword placeholders with `str.format()`


formatted_str_kw = "Name: {n}, Age: {a}, Height: {h}".format(n=name, a=age, h=height)
print(formatted_str_kw)

# 5. Using f-strings (formatted string literals)


formatted_str_fstring = f"Name: {name}, Age: {age}, Height: {height:.1f}"
print(formatted_str_fstring)

# 6. Using `%` operator for formatting numbers with placeholders


formatted_num_percent = "Formatted number: %.2f" % 1234.56789
print(formatted_num_percent)

# 7. Using `str.format()` method for formatting numbers with placeholders


formatted_num_format = "Formatted number: {:.2f}".format(1234.56789)
print(formatted_num_format)

# 8. Using f-strings for formatting numbers with placeholders


formatted_num_fstring = f"Formatted number: {1234.56789:.2f}"

GE3151 Problem Solving and Python Programming 12


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
print(formatted_num_fstring)

Output:
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Formatted number: 1234.57
Formatted number: 1234.57
Formatted number: 1234.57

3.6 Example for Formatting in Text Files


# Example for Formatting Data in Text Files

# Data to be written to the file


name = "John"
age = 25
height = 5.9
city = "New York"

# Open a file for writing (creates the file if it doesn't exist)


with open('formatted_output.txt', 'w') as file:

# 1. Using `%` operator (old-style formatting)


file.write("Using %% operator:\n")
file.write("Name: %s, Age: %d, Height: %.1f, City: %s\n\n" % (name, age, height,
city))

# 2. Using `str.format()` method (modern formatting)


file.write("Using `str.format()` method:\n")
file.write("Name: {}, Age: {}, Height: {:.1f}, City: {}\n\n".format(name, age,
height, city))

# 3. Using f-strings (formatted string literals)


file.write("Using f-strings:\n")
file.write(f"Name: {name}, Age: {age}, Height: {height:.1f}, City: {city}\n\n")

# 4. Writing a formatted list of values


numbers = [1234.56789, 9876.54321, 4567.12345]
file.write("Using f-strings to format numbers:\n")
for num in numbers:
file.write(f"Formatted number: {num:.2f}\n")

# Closing the file (done automatically by `with` block)


print("Formatted text written to 'formatted_output.txt'.")

Output in formatted_output.txt:
Using % operator:
Name: John, Age: 25, Height: 5.9, City: New York

Using `str.format()` method:


Name: John, Age: 25, Height: 5.9, City: New York

Using f-strings:
Name: John, Age: 25, Height: 5.9, City: New York

Using f-strings to format numbers:

GE3151 Problem Solving and Python Programming 13


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Formatted number: 1234.57
Formatted number: 9876.54
Formatted number: 4567.12

3.7 Example for Formatting using .Format Function


# Example program for string formatting using .format()

# Data to be formatted
name = "Alice"
age = 30
height = 5.6
city = "London"

# 1. Basic formatting with positional arguments


formatted_str_pos = "Name: {}, Age: {}, Height: {}, City: {}".format(name, age, height,
city)
print(formatted_str_pos)

# 2. Formatting with specified order using positional indexes


formatted_str_order = "City: {3}, Height: {2}, Age: {1}, Name: {0}".format(name, age,
height, city)
print(formatted_str_order)

# 3. Using keyword arguments for formatting


formatted_str_kw = "Name: {name}, Age: {age}, Height: {height}, City:
{city}".format(name=name, age=age, height=height, city=city)
print(formatted_str_kw)

# 4. Formatting numbers with a specified precision


formatted_num = "Formatted height: {:.2f}".format(height)
print(formatted_num)

# 5. Formatting with padding (aligning text)


formatted_padding = "Left aligned: {:<10}, Right aligned: {:>10}, Center aligned:
{:^10}".format(name, name, name)
print(formatted_padding)

# 6. Formatting with specified width and zero-padding


formatted_zero_padding = "Zero-padded number: {:05}".format(42)
print(formatted_zero_padding)

# 7. Using multiple values in formatting


formatted_multiple = "Name: {0}, Age: {1}, Height: {2}, City: {3}".format(name, age,
height, city)
print(formatted_multiple)

# 8. Mixing positional and keyword arguments


formatted_mixed = "Name: {0}, Age: {1}, Height: {height}, City: {city}".format(name,
age, height=height, city=city)
print(formatted_mixed)

Output:
Name: Alice, Age: 30, Height: 5.6, City: London
City: London, Height: 5.6, Age: 30, Name: Alice
Name: Alice, Age: 30, Height: 5.6, City: London
Formatted height: 5.60
Left aligned: Alice , Right aligned: Alice, Center aligned: Alice
Zero-padded number: 00042
Name: Alice, Age: 30, Height: 5.6, City: London

GE3151 Problem Solving and Python Programming 14


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Name: Alice, Age: 30, Height: 5.6, City: London

3.8 Command Line Arguments


Command Line Arguments in Python allow you to pass arguments to a Python script when running it from
the command line. This allows the script to be more dynamic, as it can accept input from the user at runtime
rather than being hardcoded. When you run a Python script from the command line, you can specify arguments
that the script will process. These arguments are passed to the script in the form of a list of strings.

a. Accessing Command Line Arguments in Python


Python provides a built-in module called sys to access command line arguments. The sys.argv list holds
all arguments passed to the script.
• sys.argv[0] is the name of the script.
• sys.argv[1] to sys.argv[n] are the arguments passed to the script.

b. Running a Python Script with Arguments:


import sys
# Print the arguments passed to the script
print("Arguments passed to the script:", sys.argv)
# Print each argument individually
for arg in sys.argv:
print(arg)

c. Running the script from the command line:


python example.py Hello World 123

Output
Arguments passed to the script: ['example.py', 'Hello', 'World', '123']
example.py
Hello
World
123

GE3151 Problem Solving and Python Programming 15


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
4. PYTHON ERROR HANDLING
4.1 Python Errors
In Python, errors refer to issues that arise during the execution of a program. When Python encounters an
error, it typically raises an exception, which interrupts the program's flow. The Python interpreter can either
handle these errors or terminate the program, depending on how the error is managed. Python errors can be
broadly classified into the following categories:
• Syntax Errors
• Runtime Errors
• Logical Errors

a. Syntax Errors
• Description: Syntax errors occur when the code does not follow the correct syntax of the Python
language. These errors are usually detected by the Python interpreter before the program runs.
• Example:
print("Hello, World!"

Error: Missing closing parenthesis.


o The correct version should be:
print("Hello, World!")

b. Runtime Errors (Exceptions)


• Description: Runtime errors occur while the program is running, often due to invalid operations,
such as dividing by zero, accessing a nonexistent index, or calling a function with incorrect
arguments. These errors are handled using try and except blocks.

• Example:
x = 10 / 0 # This will raise a ZeroDivisionError
Error: ZeroDivisionError because dividing by zero is not allowed.

c. Logical Errors
• Description: Logical errors occur when the program runs without crashing but does not produce the
correct result. These errors are typically due to incorrect logic in the code, which can be difficult to
debug.

• Example:
def add_numbers(a, b):
return a - b # This is a logical error, it should be addition, not subtraction

result = add_numbers(3, 4)
print(result) # Output will be incorrect (it will print 1 instead of 7)

Error: The function does not perform the correct operation due to the wrong use of the subtraction
operator instead of addition.

4.2 Exception Handling


Exception handling in Python is a mechanism that allows you to handle runtime errors (also known as
exceptions) in a structured and controlled way. Instead of the program terminating abruptly when an error
occurs, you can catch these errors, handle them, and allow the program to continue executing.

GE3151 Problem Solving and Python Programming 16


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
An exception is an event that disrupts the normal flow of a program's execution. When Python encounters
an error (exception), it raises an exception object, which can be caught and processed using try, except,
else, and finally blocks.

a. Key Components of Exception Handling:


1. try: The code that might raise an exception is placed inside a try block.
2. except: If an exception occurs in the try block, it is caught by the except block, where you can handle
it.
3. else: If no exception occurs in the try block, the code inside the else block runs.
4. finally: This block runs no matter what, regardless of whether an exception occurred or not. It is often
used for clean-up tasks (like closing files or releasing resources).

b. Syntax of Exception Handling:


try:
# Code that might raise an exception
code_that_might_fail()
except ExceptionType as e:
# Code to handle the exception
handle_the_error(e)
else:
# Code that runs if no exception occurs
code_to_run_if_no_error()
finally:
# Code that runs no matter what
cleanup_code()

• try: Code that may raise an exception is written here.


• except: If an exception occurs in the try block, it is handled here.
• else: This block runs only if no exception occurs.
• finally: This block runs regardless of whether an exception occurs or not.

c. Example
try:
# Trying to divide by zero
result = 10 / 0
except ZeroDivisionError:
# This block will run if a ZeroDivisionError occurs
print("Error: You can't divide by zero!")

try:
# Asking the user to input a number
number = int(input("Enter a number: "))
print(f"You entered: {number}")

except ValueError:
# This block will run if a ValueError occurs (non-numeric input)
print("Error: That's not a valid number!")

4.3 Python Exceptions


In Python, exceptions are events that occur during the execution of a program and disrupt its normal flow.
They are typically caused by errors in the program, such as dividing by zero, trying to open a file that doesn’t
exist, or passing an invalid argument to a function. An exception is a signal that an error has occurred, and

GE3151 Problem Solving and Python Programming 17


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Python provides a way to handle these errors through exception handling mechanisms. Handling exceptions
allows your program to continue executing even when errors occur, rather than terminating unexpectedly.

a. Exception Types
The following are the types of exceptions in Python.

Error Type Description Example


Raised when a division or modulo
x = 10 / 0 (Raises
ZeroDivisionError operation is performed with zero as the
ZeroDivisionError)
divisor.
Raised when a function receives an
ValueError argument of the correct type but an int("hello") (Raises ValueError)
inappropriate value.
Raised when trying to access an index in a my_list = [1, 2, 3];
IndexError list, tuple, or other indexed collections that print(my_list[5]) (Raises
is out of range. IndexError)
my_dict = {'a': 1};
Raised when trying to access a dictionary
KeyError print(my_dict['b']) (Raises
with a key that doesn’t exist.
KeyError)
Raised when an operation or function is
TypeError "hello" + 5 (Raises TypeError)
applied to an object of inappropriate type.
my_string = "hello";
Raised when an attribute reference or
AttributeError my_string.append(" world")
assignment fails.
(Raises AttributeError)
Raised when trying to open a file that does open("non_existent_file.txt",
FileNotFoundError
not exist. "r") (Raises FileNotFoundError)
Raised when an import statement fails to
import non_existent_module
ImportError import a module or a specific name from a
(Raises ImportError)
module.
Raised when the result of an arithmetic
import math; math.exp(1000)
OverflowError operation is too large to be expressed
(Raises OverflowError)
within the range of a numeric type.
Raised when the next() function is called iterator = iter([1, 2]);
StopIteration on an iterator and there are no more items next(iterator) (Raises
to return. StopIteration)
Raised when an operation runs out of a = [1] * (10**10) (Raises
MemoryError
memory. MemoryError)
Raised when an abstract method in an class BaseClass: def
NotImplementedError abstract class is not implemented in a some_method(self): raise
subclass. NotImplementedError()

Example Program:
# ZeroDivisionError
try:
print("ZeroDivisionError Example:")
x = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
print()

GE3151 Problem Solving and Python Programming 18


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
# ValueError
try:
print("ValueError Example:")
x = int("abc")
except ValueError as e:
print(f"Error: {e}")
print()

# IndexError
try:
print("IndexError Example:")
my_list = [1, 2, 3]
print(my_list[5])
except IndexError as e:
print(f"Error: {e}")
print()

# KeyError
try:
print("KeyError Example:")
my_dict = {"name": "Alice", "age": 25}
print(my_dict["address"])
except KeyError as e:
print(f"Error: {e}")
print()

# TypeError
try:
print("TypeError Example:")
x = "hello" + 5
except TypeError as e:
print(f"Error: {e}")
print()

# AttributeError
try:
print("AttributeError Example:")
class Person:
def __init__(self, name):
self.name = name

p = Person("Alice")
print(p.age) # Attribute does not exist
except AttributeError as e:
print(f"Error: {e}")
print()

# FileNotFoundError
try:
print("FileNotFoundError Example:")
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError as e:
print(f"Error: {e}")
print()

# ImportError
try:
print("ImportError Example:")
import non_existent_module

GE3151 Problem Solving and Python Programming 19


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
except ImportError as e:
print(f"Error: {e}")
print()

# OverflowError
try:
print("OverflowError Example:")
x = 1e1000 # A very large number
except OverflowError as e:
print(f"Error: {e}")
print()

# StopIteration
try:
print("StopIteration Example:")
my_list = [1, 2, 3]
it = iter(my_list)
while True:
print(next(it))
except StopIteration as e:
print(f"Error: {e}")
print()

# MemoryError
try:
print("MemoryError Example:")
large_list = [1] * (10**10) # Trying to allocate too much memory
except MemoryError as e:
print(f"Error: {e}")
print()

# NotImplementedError
try:
print("NotImplementedError Example:")
class Animal:
def make_sound(self):
raise NotImplementedError("Subclasses must implement this method")

animal = Animal()
animal.make_sound()
except NotImplementedError as e:
print(f"Error: {e}")

GE3151 Problem Solving and Python Programming 20


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
5. PYTHON MODULES
5.1 What is a Python Module?
• A Python module is a file containing Python definitions and statements, such as functions, classes, and
variables, which can be used in other Python programs.
• Essentially, a module is a way to organize code and make it reusable.
• You can think of it as a container for related code that can be imported into other Python scripts to avoid
redundancy.
• Python comes with many built-in modules that provide functionality for various tasks, such as
mathematical operations, random number generation, and working with dates and times.

5.2 How to Use a Python Module


You can import and use a module in Python using the import statement. Once imported, you can access the
functions and variables defined in that module.

5.3 Example of importing a module


import math # Importing the math module

5.4 Examples of Built-in Python Modules


1. Random Module
The random module is used to generate random numbers or select random items from a list.

Example:
import random

# Generate a random integer between 1 and 100


random_integer = random.randint(1, 100)
print(f"Random integer: {random_integer}")

# Choose a random element from a list


my_list = ['apple', 'banana', 'cherry']
random_choice = random.choice(my_list)
print(f"Random choice from list: {random_choice}")

2. Math Module
The math module provides mathematical functions such as calculating square roots, trigonometric
operations, and constants like π (pi).

Example:
import math

# Calculate the square root of a number


sqrt_value = math.sqrt(16)
print(f"Square root of 16: {sqrt_value}")

# Calculate the value of pi


pi_value = math.pi
print(f"Value of pi: {pi_value}")

# Find the sine of a number (angle in radians)


sine_value = math.sin(math.pi / 2)
print(f"Sine of 90 degrees (pi/2 radians): {sine_value}")

3. Calendar Module

GE3151 Problem Solving and Python Programming 21


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
The calendar module provides functions to work with calendars, such as displaying a month's calendar or
checking if a year is a leap year.

Example:
import calendar
# Print the calendar for the month of December 2024
print(calendar.month(2024, 12))
# Check if a year is a leap year
is_leap = calendar.isleap(2024)
print(f"Is 2024 a leap year? {is_leap}")

4. Datetime Module
The datetime module supplies classes for manipulating dates and times, like obtaining the current date or
performing date arithmetic.
Example
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(f"Current date and time: {now}")
# Extract specific parts of the current date
current_date = now.date()
current_time = now.time()
print(f"Current date: {current_date}")
print(f"Current time: {current_time}")
# Format the date in a specific format
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")

6. PYTHON PACKAGE
A Python package is a way of organizing related modules into a single directory hierarchy. It allows you to
structure your Python code in a more modular and reusable manner. A package is essentially a directory
containing multiple Python modules (files with .py extension) and a special file called __init__.py, which tells
Python that this directory should be treated as a package. In simpler terms, a package is a collection of
modules, and a module is a collection of functions, classes, and variables.

Structure of a Python Package


A Python package typically has the following structure:

6.1 Packages in Python


In Python, packages are a way of organizing and structuring Python code into multiple modules and
submodules, making it easier to manage and reuse. A package is essentially a directory that contains Python
modules and a special file called __init__.py. This __init__.py file signifies that the directory should
be treated as a Python package and can contain initialization code for the package.

GE3151 Problem Solving and Python Programming 22


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science

6.2 Understanding Python Packages


A package is a collection of modules that are grouped together. A module is a single file containing Python
code, whereas a package is a directory that contains multiple modules, and possibly sub-packages. A
package may also contain other resources, such as configuration files, data files, or documentation.

6.3 Structure of a Package:


A typical package structure looks like this:
my_package/
__init__.py
module1.py
module2.py
sub_package/
__init__.py
sub_module1.py
sub_module2.py

• __init__.py: This special file is used to mark the directory as a package. The file can be empty
or contain initialization code for the package.
• module1.py, module2.py: These are Python modules that contain the actual code for your
package.
• sub_package/: A package can contain sub-packages, which themselves are directories with their
own __init__.py files.

6.4 Creating a Package


To create a package, you simply create a directory with one or more Python modules and include an
__init__.py file to indicate that the directory is a package.
For example:
1. Create a directory for the package:
my_package/
2. Inside that directory, create Python files:
o module1.py
o module2.py
3. Create the __init__.py file, which can be empty or include initialization code:
# __init__.py
print("My Package has been initialized!")

6.5 Importing from a Package:


Once a package is created, you can import its modules using the import statement.
a. Importing a module from a package:
import my_package.module1

b. Importing specific functions or classes from a module:


from my_package.module1 import my_function

c. Importing a sub-package:
import my_package.sub_package.sub_module1

d. Using as to alias a module or submodule:


import my_package.module1 as m1

GE3151 Problem Solving and Python Programming 23


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science

Example: Simple Package


Let's create a simple package with two modules:

Package Structure:
my_math/
__init__.py
addition.py
subtraction.py

Content of addition.py:
# addition.py
def add(a, b):
return a + b

Content of subtraction.py:
# subtraction.py
def subtract(a, b):
return a - b

Content of __init__.py:
# __init__.py
print("My Math Package Initialized")

Using the Package in Code:


# main.py
import my_math.addition as add
import my_math.subtraction as sub

result_add = add.add(5, 3)
result_sub = sub.subtract(5, 3)

print(f"Addition Result: {result_add}")


print(f"Subtraction Result: {result_sub}")

Output:
My Math Package Initialized
Addition Result: 8
Subtraction Result: 2

7. PICKLING
Pickling in Python refers to the process of converting a Python object (such as a list, dictionary, or class
instance) into a byte stream so that it can be saved to a file, transmitted over a network, or stored in a database.
The purpose of pickling is to enable easy storage and retrieval of Python objects. Pickling is essentially the
process of serializing Python objects, which means converting complex data structures into a format that can
be easily stored or transmitted. The opposite process of pickling is called unpickling, which refers to the
process of converting the byte stream back into the original Python object. In Python, pickling is done using
the pickle module, which provides methods to serialize (pickle) and deserialize (unpickle) Python objects.

Key Functions in the pickle Module:


1. pickle.dump(obj, file) – Serializes an object and writes it to a file.
2. pickle.load(file) – Reads a pickled object from a file and returns it as a Python object.
3. pickle.dumps(obj) – Serializes an object to a byte stream (returns bytes).
4. pickle.loads(byte_stream) – Deserializes a byte stream to a Python object.

GE3151 Problem Solving and Python Programming 24


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science

Example of Pickling and Unpickling:


import pickle

# A Python dictionary object


data = {'name': 'John', 'age': 30, 'city': 'New York'}

# Pickling the object to a file


with open('data.pkl', 'wb') as f:
pickle.dump(data, f)

# Unpickling the object from the file


with open('data.pkl', 'rb') as f:
loaded_data = pickle.load(f)

print("Loaded Data:", loaded_data)

8. ILLUSTRATIVE PROGRAMS
a. File Compare
# Ask the user for the paths of the two files to compare
file1_path = input("Enter the path of the first file: ")
file2_path = input("Enter the path of the second file: ")

# Open both files in binary read mode


file1 = open(file1_path, 'rb')
file2 = open(file2_path, 'rb')

# Read the contents of both files


content1 = file1.read()
content2 = file2.read()

# Compare the contents of the two files


if content1 == content2:
print("The files are identical.")
else:
print("The files are different.")

# Close both files


file1.close()
file2.close()

b. File Copy
# Ask the user for the source and destination file paths
source_file = input("Enter the path of the source file: ")
destination_file = input("Enter the path of the destination file: ")

# Open the source file in read mode


source = open(source_file, 'rb')

# Open the destination file in write mode (create a new file or overwrite if it exists)
destination = open(destination_file, 'wb')

# Read the content of the source file and write it to the destination file
content = source.read()
destination.write(content)

# Close both files


source.close()

GE3151 Problem Solving and Python Programming 25


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
destination.close()

print(f"File has been successfully copied from {source_file} to {destination_file}.")

c. Words Count
# Ask the user for the path to the text file
file_path = input("Enter the path to the text file: ")

# Try opening and reading the file


file = open(file_path, 'r')

# Read the entire content of the file


text = file.read()

# Split the text into words based on whitespace


words = text.split()

# Count the number of words


word_count = len(words)

# Print the word count


print(f"The file contains {word_count} words.")

# Close the file


file.close()

d. Voter’s Age Validation


# Function to validate age
def validate_age(age):
try:
# Check if the age is a valid number
age = int(age)

# Check if the age is within the valid voting age range (18-120)
if 18 <= age <= 120:
return age
else:
raise ValueError("Age must be between 18 and 120 to be eligible to vote.")
except ValueError as e:
# Catch invalid input or out-of-range age
print(f"Invalid input: {e}")
return None

# Function to get age from the user and validate it with I/O error handling
def get_age():
while True:
try:
age_input = input("Enter your age to check if you're eligible to vote: ")

# Simulating an I/O error if the input is empty


if not age_input:
raise IOError("Input cannot be empty. Please provide a valid age.")

# Validate the input age


validated_age = validate_age(age_input)

if validated_age is not None:


return validated_age
else:

GE3151 Problem Solving and Python Programming 26


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
print("Please try again with a valid age.")

except IOError as io_error:


print(f"I/O Error: {io_error}. Please enter your age again.")

# Main function to execute the program


def main():
age = get_age()
print(f"Validated Age: {age}. You are eligible to vote!" if 18 <= age <= 120 else
"You are not eligible to vote.")

# Run the program


if __name__ == "__main__":
main()

e. Marks Range (0-100) Validation


# Function to validate the marks
def validate_marks(marks):
try:
# Check if the marks are a valid number
marks = float(marks)

# Check if the marks are within the valid range (0-100)


if 0 <= marks <= 100:
return marks
else:
raise ValueError("Marks must be between 0 and 100.")
except ValueError as e:
# Catch invalid input or out-of-range marks
print(f"Invalid input: {e}")
return None

# Function to get marks from user and validate


def get_marks():
while True:
marks_input = input("Enter marks (0-100): ")

# Validate the marks input


validated_marks = validate_marks(marks_input)

if validated_marks is not None:


return validated_marks
else:
print("Please try again with valid marks.")

# Main function to execute the program


def main():
marks = get_marks()
print(f"Validated Marks: {marks}")

# Run the program


if __name__ == "__main__":
main()

Sample Output:
Enter marks (0-100): 105
Invalid input: Marks must be between 0 and 100.
Please try again with valid marks.
Enter marks (0-100): abc

GE3151 Problem Solving and Python Programming 27


PGP College of Engineering and Technology Department of Artificial Intelligence and Data Science
Invalid input: could not convert string to float: 'abc'
Please try again with valid marks.
Enter marks (0-100): 85
Validated Marks: 85.0
NOTES
_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

_______________________________________________________________________________________

GE3151 Problem Solving and Python Programming 28

You might also like