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

Python - Unit IV

This document covers file handling in Python, including file I/O operations, types of files, and methods for reading and writing files. It explains the differences between text and binary files, how to open and close files, and various file modes. Additionally, it provides illustrative programs for practical understanding, such as searching for strings in files and finding the one's complement of binary numbers.
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)
2 views

Python - Unit IV

This document covers file handling in Python, including file I/O operations, types of files, and methods for reading and writing files. It explains the differences between text and binary files, how to open and close files, and various file modes. Additionally, it provides illustrative programs for practical understanding, such as searching for strings in files and finding the one's complement of binary numbers.
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/ 25

UNIT 4

FILES, EXCEPTIONS, MODULES AND PACKAGES

Files and exception: Text Files, Reading and Writing files, Format operator; Errors and Exceptions,
Handling Exceptions, Multiple Except blocks, Modules, Packages; Illustrative programs: word count,
copy file, Creating user defined Exceptions.

FILES AND EXCEPTION: TEXT FILES, READING AND WRITING FILES

1. Write a Python program to demonstrate the file I/O operations.


2. Discuss the different modes for opening a file and closing a file.
17. Discuss the different modes for opening a file and closing a file.
5. (i) Explain with example of writing a file (ii) Discover syntax for reading from a file.
6. Explain about the files related methods with example coding.

What is a File?
• A file is a collection of data stored on a secondary storage device like a hard disk.
• Initially, data was entered using the input() function, which is fine for small data.
• But when data becomes large, it becomes tedious and inefficient to process it manually each
time.
• Better solution: Combine data into a file and use a Python program to read/write from it
when needed.

Volatile vs Non-Volatile Memory


• When a program runs, its data is stored in RAM (Random Access Memory).
• RAM is fast but volatile – data is lost when the program ends or the computer shuts down.
• To save data permanently, it should be stored on non-volatile media like:
o Hard Disk
o USB Drive
o DVD
o etc.

What are Files?


• Data on storage media is saved in files – named locations where data is stored.
• A file can be compared to a notebook:
o Open it to read/write
o Close it after using
• In Python: we first open a file, then read or write, and finally close it.

File I/O Basics


• Input ➝ Reading data from a file
Output ➝ Writing data to a file
• File I/O (Input/Output) is about reading from or writing to a file.
• The process is similar to using a notebook:
o Open → Read/Write → Close
• The user must specify the file name and mode (read/write) to perform file I/O.

1
Basic Steps in File I/O:
1. Open the file (for reading, writing, or both)
2. Read from or write to the file
3. Close the file (to free up system resources)

FILE PATH
• Files are stored on a storage medium like a hard disk.
• The storage is organized so that files can be easily retrieved whenever required.
• Most modern file systems store files in a tree (or hierarchical) structure.
• This hierarchical system allows files to be organized in folders and subfolders, making it easier
to manage and locate them.

What is a File Path?


• A file path shows the location of a file or folder in the computer.
• It starts from the root folder (like C:\ in Windows).
• The path helps the computer find the exact file or folder.

Structure of Files and Folders:


• At the top is the root (example: C:\).
• Inside the root, there are folders (like Students, Teachers, Staff).
• Folders can have subfolders and files inside them.

Example:
File: BTech_CS.docx
Location:
C:\Students\Under Graduate\BTech_CS.docx
Explanation:

• C: – Root drive
• Students – Folder
• Under Graduate – Subfolder
• BTech_CS.docx – File

TYPES OF FILE

1. ASCII Text Files


• A text file is a stream of characters.
• It can be read or written in a sequence, one character at a time.
• Mostly used for one purpose at a time: read, write, or append.

2
• Text files process characters, not raw data like binary files.
• They are human-readable.
• A line can have up to 255 characters.
• Each line ends with newline characters.
• The file ends with a special character called EOF (End Of File).
• After the last line of the file, the computer adds a hidden marker called EOF.
• EOF = End Of File
Apple\n
• It tells the computer:
Banana\n
👉 “Stop reading! The file is over.” Orange\n
EOF

The computer reads:


Apple (newline)
Banana (newline)
Orange (newline)
Then it sees EOF and stops.

2. Binary Files

• A binary file stores any type of data in binary form (e.g., documents, images, PDFs, programs).
• It is different from a text file in that it handles bytes rather than characters.
• No special processing is needed; each byte is transferred as-is to/from disk.
• Python allows reading/writing binary files in any format without restrictions.
• Binary files can be accessed sequentially or randomly depending on the application's needs.
• When updating binary data (e.g., student records), the programmer:
o Locates the required record,
o Reads it into memory,
o Modifies it,
o Writes it back to the appropriate file location.

✓ Binary files store data in internal representation (e.g., integers stored as 2-byte values).
✓ Binary files, like text files, end with an EOF (End of File) marker.
✓ In a text file, an integer like 123 is stored as 3 characters: '1', '2', and '3', requiring 3 bytes.
✓ In a binary file, the same integer 123 is stored in 2 bytes in binary form.
✓ Binary files are more efficient in terms of storage and processing since they:
o Take less space,
o Avoid conversion between internal and external data representations.

Aspect Text Files Binary Files


Storage Format Characters Binary (internal format)
File Size Larger (e.g., 123 = 3 bytes) Smaller (e.g., 123 = 2 bytes)
Readability Readable in text editors Appears scrambled in text editors
Extensions .txt, .py, etc. .exe, .jpg, .dat, etc.
Usage Storing plain text/code Storing non-text data like images, videos, executables

3
FILE I/O OPERATIONS

1. OPENING AND CLOSING FILES

Python provides many in-built functions and methods to manipulate files, which primarily operate on
file objects.

i) The open() Function

• Purpose:
Before reading from or writing to a file, you must open it using Python’s built-in open()
function. This function creates a file object used to invoke file-related methods.

Syntax: fileObj = open(file_name [, access_mode])

Parameters:

• file_name: A string representing the name of the file you want to access.
• access_mode: (Optional) A string that indicates the mode of file access, e.g., read (r), write
(w), append (a), etc.
• If access_mode is not specified, the default mode is read (r).

Return Value:

• The open() function returns a file object, which allows operations such as reading, writing, or
appending.
• It behaves like a file handle.

Example:
file = open("File1.txt", "rb")
print(file)
Output: <open file 'File1.txt', mode 'rb' at 0x02A850D0>

rb - Read Binary Mode – It opens the file for reading in binary format (not as text).

Mode Meaning Details


r Read Default mode. Opens file for reading. File must exist. Pointer is placed at the
beginning of the file.
rb Read (binary) Opens file for reading in binary format. File must exist. Pointer at beginning.
r+ Read & Write Opens file for both reading and writing without deleting its contents. File
must exist. Pointer at beginning.
rb+ Read & Write Same as r+, but in binary mode. File must exist. Pointer at beginning.
(binary) ✓ Opens existing file for both reading and writing in binary mode
without deleting data.
w Write Opens file for writing. Creates new file or overwrites if it exists. Pointer at
beginning.
wb Write (binary) Same as w, but in binary mode. Overwrites existing file or creates new one.
w+ Write & Read Opens for writing and reading but clears contents or creates a new file if it
doesn’t exist. Overwrites existing file or creates new one.
wb+ Write & Read Same as w+, but in binary mode. Overwrites or creates file.
(binary) ✓ Opens a file for reading and writing in binary mode, but first clears
its contents or creates a new file if it doesn't exist.

4
a Append Opens for appending. Pointer at end You can only add content to the end of
the file. Creates file if not exists. Keeps existing content. Write-only mode.
ab Append (binary) Same as a, but in binary mode. Appends data at end.
a+ Append & Read Opens for reading and appending. Pointer at end, writing always happens at
the end. Creates file if not exists.
ab+ Append & Read Same as a+, but in binary mode. Pointer at end. Creates file if not exists.
(binary)

ii) File Object Attributes in Python

Once a file is opened using the open() function, it returns a file object. This object provides various
attributes to get information about the file.

Attribute Description
fileObj.closed Returns True if the file is closed, False if it's still open.
fileObj.mode Returns the access mode used to open the file (e.g., "r", "wb+").
fileObj.name Returns the name of the file.

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

print(file.closed) # False
print(file.mode) # 'r'
print(file.name) # 'example.txt'

file.close()
print(file.closed) # True

iii) The close() Method

Purpose:
The close() method is used to close a file object in Python. Once closed, you cannot read from or
write to the file.

Functionality:

• Flushes any unwritten data to the file (ensures all buffered output is written to disk).
• Frees system resources like file descriptors, file locks, etc., that are tied to the file.

5
Syntax: fileObj.close()

Important Notes:

• Python may automatically close a file when the reference is reassigned, but it's good practice
to always close files explicitly using close().
• Not closing files can lead to:
o Memory wastage
o Hitting the limit of open files, which may crash the program
o Data loss or corruption
• After calling close(), any operation on the file object will raise an error.

2. READING AND WRITING FILES

• Purpose: read() and write() functions are used to read from and write to files.

i) write() and writelines() Methods

▪ write() Method
✓ Used to write a string to an already opened file.
✓ Can include:
o Numbers
o Special characters
o Symbols

Note: write() does not add a newline (\n) at the end automatically.

6
Syntax: fileObj.write(string)
The string passed as an argument is written directly into the opened file.

When you write the following to a file:


fileObj.write("Hello All, hope you are enjoying learning Python")

and open File1.txt, it will contain:


Hello All, hope you are enjoying learning Python
✓ The write() method returns None.

▪ writelines() method → is used to write a list of strings.

ii) append() Method

• After storing data in a file, you can open it again to append more data.
• This is done using:
o 'a' mode for text files
o 'ab' mode for binary files
• Appending allows adding content without overwriting the existing data in the file.

• If you open a file in 'w' (write) or 'wb' (write binary) mode and write data, existing contents will be
overwritten.

✓ To preserve existing data and add new data, always use:


• 'a' (append) mode for text files
• 'ab' (append binary) mode for binary files

7
iii) read() and readline() Methods

➢ read() Method:

• Purpose: Used to read a string from an already opened file.


• Content Read: The string may include alphabets, numbers, characters, or other symbols.

Syntax: fileObj.read([count])

• Parameters:
o count (optional): Specifies the number of bytes to read from the file.
o If count is not provided or has a negative value, the entire file content is read.
• Behavior:
o Begins reading from the start of the file.
o If count is provided, reads up to count bytes.
o If not, reads until the end of the file.

8
➢ readline() Method

• Reads a single line from the file each time it is called.


• Returns a string containing the line read from the file.
• Returns an empty string ("") when the end of the file (EOF) is reached.

Notes:
• A blank line in a file is represented by \n.
• When a blank line is encountered, the method returns a string with only the newline
character ('\n').
• read() method also includes newline characters (\n) in its output.

➢ readlines() Method

• Purpose: Reads all lines from a file into a list of strings.

Syntax: file.readlines()
• Returns: A list, where each item is a line from the file, including \n.

9
➢ Using list() to Read File Contents

✓ The list() function can be used to display the entire contents of a file.
✓ Pass the file object to the list() function:
file = open("example.txt", "r")
content = list(file)
print(content)

• Each line of the file becomes an element in the list.


• Similar to using readlines(), but done through a built-in function.
🔹 Output: Returns a list of strings, where each string represents a line from the file (including \n
characters).

➢ Splitting Words

• Python allows you to read line(s) from a file and split the line into words.
• The line is treated as a string, and you can use the .split() method to divide it based on a
separator character.
• By default, .split() uses space (" ") as the delimiter.
• You can specify any character as the delimiter:

line = "apple,banana,cherry"
words = line.split(",")
print(words) # ['apple', 'banana', 'cherry']

✓ Often used after reading a line from a file to process individual words or tokens.

8. Write a program that will prompt the user for a string and a file name, and then print all lines in
the file that contain the string. Also interpret the obtained result.

Program:
search_string = input("Enter the string to search for: ")
filename = input("Enter the file name: ")

try:
file = open(filename, 'r')
for line in file:
if search_string in line:
print(line.strip())
file.close()

10
except:
print("Error: File not found or could not be opened.")

• It asks for a search string and file name.


• It opens the file and checks each line.
• If the line contains the search string, it prints the line.
• If there's a problem (like file not found), it shows an error.
• The program searched every line.
• It printed the lines where the word "Python" appeared.
• Other lines without "Python" were ignored.

Suppose you have a file called example.txt with the following content:
Welcome to Python programming.
This course is about learning coding.
Python is very easy to learn.
We are practicing file handling today.
Good luck with your learning!

Output: Enter the string to search for:


Python
Enter the file name: example.txt

Welcome to Python programming.


Python is very easy to learn.

10. Illustrate a program to find the one’s complement of binary number using file.

Program
filename = input("Enter the file name: ")# Step 1: Ask the user to enter the file
name

try:
file = open(filename, 'r') # Step 2: Try to open the file in 'read'
mode
binary = file.read().strip() # Step 3: Read the content and remove
any extra spaces or newlines
file.close() # Step 4: Close the file after reading

ones_complement = '' # Step 5: Create an empty string to


store one's complement
for bit in binary: # Step 6: Go through each bit (character) in the binary number
if bit == '0': # Step 7: If the bit is 0, change it to 1
ones_complement += '1'
else: # Step 8: If the bit is 1, change it to 0
ones_complement += '0'

print("Original binary number:", binary)# Step 9: Print the original binary number
print("One's complement:", ones_complement) # Step 10: Print the one's complement

except: # Step 11: If there is any problem (like file not found), show this message
print("Error: File not found or invalid content.")

Output: If binary.txt contains: 1010

11
When you run the program:

Enter the file name: binary.txt


Original binary number: 1010
One's complement: 0101

13. Write a program to count the total number of uppercase characters in a file.

Program
def count_uppercase_characters(filename):
count = 0
try:
with open(filename, 'r') as file:
for line in file:
for char in line:
if char.isupper():
count += 1
print(f"Total number of uppercase characters: {count}")
except FileNotFoundError:
print(f"The file '{filename}' was not found.")

# Example usage
filename = input("Enter the filename: ")
count_uppercase_characters(filename)

Explanation
• It asks the user to enter the filename.
• Then it calls the function with the filename.
• A function named count_uppercase_characters is created.
• It takes one input called filename (the name of the file you want to check).
• A variable count is set to 0.
• It will be used to count how many uppercase letters are found.
• try means you are trying to open the file safely.
• open(filename, 'r') opens the file in read mode ('r').
• with ensures the file is automatically closed after reading.
• for line in file: This loop reads the file one line at a time.

o char.isupper() checks if the character is uppercase (like A, B, Z).


o If yes, count += 1 adds one to the count.
• After the whole file is read, the total count of uppercase letters is printed.

Output

Suppose you have a file called sample.txt with this content:


Hello World
This is a Test FILE.
Python Is Fun!

• Open sample.txt
• Check each character in every line
• Count only the uppercase letters: H, W, T, T, F, I, P, I, F

12
• So total uppercase characters = 9

Thus, your output will be:

Enter the filename: sample.txt


Total number of uppercase characters: 9

If the filename you type does not exist, you will see:

Enter the filename: notfound.txt


The file 'notfound.txt' was not found.

16. Explain with an example to copy the contents of one file to another.

To copy contents from one file to another in Python, you can:

• Open the source file in read mode ('r').


• Open the destination file in write mode ('w').
• Read from the source and write into the destination.

Program
def copy_file(source_file, destination_file):
try:
with open(source_file, 'r') as src:
with open(destination_file, 'w') as dest:
for line in src:
dest.write(line)
print(f"Contents copied from '{source_file}' to '{destination_file}'
successfully.")
except FileNotFoundError:
print(f"The file '{source_file}' was not found.")

# Example usage
source = input("Enter the source filename: ")
destination = input("Enter the destination filename: ")
copy_file(source, destination)

Output
Suppose you have a file called source.txt with content:
Hello Students,
Welcome to Python Programming.

When you run the program:


Enter the source filename: source.txt
Enter the destination filename: destination.txt

The program will create a file destination.txt with the same content:
Hello Students,
Welcome to Python Programming.
Contents copied from 'source.txt' to 'destination.txt' successfully.

13
18. Write a program that reads the contents of the file text.txt and counts the number of alphabets,
blank spaces, lowercase letters and uppercase letters, the number of words starting with a vowel,
and the number of occurrences of each word in the file.
import re
from collections import Counter

def is_vowel(word):
return word[0].lower() in 'aeiou'

# Open and read the file


with open('text.txt', 'r') as file:
text = file.read()

# Initialize counters
alphabet_count = sum(c.isalpha() for c in text)
blank_space_count = text.count(' ')
lowercase_count = sum(c.islower() for c in text)
uppercase_count = sum(c.isupper() for c in text)

# Split words using regex to handle punctuation properly


words = re.findall(r'\b\w+\b', text.lower()) # make lowercase for consistent
word counting

# Count words starting with a vowel


vowel_start_count = sum(1 for word in words if is_vowel(word))

# Count occurrences of each word


word_occurrences = Counter(words)

# Display results
print(f"Number of alphabets: {alphabet_count}")
print(f"Number of blank spaces: {blank_space_count}")
print(f"Number of lowercase letters: {lowercase_count}")
print(f"Number of uppercase letters: {uppercase_count}")
print(f"Number of words starting with a vowel: {vowel_start_count}")
print("Occurrences of each word:")
for word, count in word_occurrences.items():
print(f"{word}: {count}")

Output

Let's assume the text.txt contains this text:

Apple is a fruit. Orange is also a fruit. Banana is not a vegetable.

Number of alphabets: 61
Number of blank spaces: 14
Number of lowercase letters: 47
Number of uppercase letters: 3
Number of words starting with a vowel: 6
Occurrences of each word:
apple: 1
is: 3
a: 3

14
fruit: 2
orange: 1
also: 1
banana: 1
not: 1
vegetable: 1

Explanation

➢ Reads the file text.txt.


➢ Counts:
• Alphabets (isalpha() check)
• Blank spaces (text.count(' '))
• Lowercase letters (islower())
• Uppercase letters (isupper())
➢ Splits words properly (using regex to avoid issues with punctuation like commas or periods).
➢ Counts words starting with vowels (a, e, i, o, u).
➢ Counts occurrences of each word (case-insensitive).

ERRORS AND EXCEPTIONS, HANDLING EXCEPTIONS

9. Describe in detail exception handling with sample program.

12. Explain the terminology of raising an exception concept with sample program.

ERROR
An error is an abnormal condition or defect that occurs during program execution, making it
impossible for the program to continue running normally.

Types

i) Syntax Errors: Arise from poor understanding of the language. Can be detected through debugging
and testing.
✓ Syntax errors occur when we violate the rules of Python.
✓ These are the most common errors faced by beginners.
Example: i = 0
if i == 0 print(i) Correct Code: i=0
if i == 0:
You must add a colon (:) after the if condition. print(i)

15
ii) Logic Errors: Logic errors occur when the program runs without crashing but produces incorrect
results. They happen due to wrong algorithms or wrong logical flow.

Examples:
1. Wrong logic in division:
a = 10
b = 5
print("Result:", a + b) # Wrong logic, should be division

o Expected: 2
o Actual Output: 15
2. Accessing wrong index in a list:
items = [1, 2, 3]
print(items[5]) # Index out of bounds
Important:
Logic errors can sometimes lead to runtime errors (called exceptions) like:
• ZeroDivisionError
• IndexError (list index out of range)

EXCEPTION
An exception is an event that occurs during the execution of a program that disrupts the normal flow
of instructions but can usually be handled using proper code (like try-except blocks).

✓ Even if a program is syntactically correct, it can still cause errors while running. Such errors
during execution are called exceptions.
✓ Represent anomalies or unusual conditions like:
o Divide by zero
o Array index out of bounds
o Running out of memory or disk space
o Overflow and underflow

Types
i) Synchronous Exceptions:
o Occur due to program's actions (e.g., divide by zero, array out of bounds).
o Can be controlled by the program.
Example
a = 10
b = 0
print(a / b)

• This will raise a ZeroDivisionError because division by zero is not allowed.

Handling the Exception:


a = 10
b = 0
try:
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero!")

• Now, the program handles the error gracefully without crashing.

16
ii) Asynchronous Exceptions:
o Caused by external events (e.g., keyboard interrupt, hardware malfunction, disk
failure).
o Beyond the control of the program.

HANDLING EXCEPTIONS

• Definition:
We can handle errors in a program using the try block and except block.
• Purpose:
o Code that might cause an error is written inside the try block.
o Code that handles the error is written inside the except block.
Syntax:

try:
statements
except ExceptionName:
statements

1. Step 1:
The code inside the try block is executed first.
2. Step 2a:
If no error occurs → the except block is skipped.
3. Step 2b:
If an error occurs while running the try block:
o i. Remaining statements inside try are skipped.
o ii. If the error matches the ExceptionName, the except block is executed.
o iii. If no matching except block is found → the program stops with an error
message (called Unhandled Exception).

17
RAISING AN EXCEPTION

• Raising an Exception means manually creating an exception in your program using the raise
keyword.
• It is used when you want to trigger an error intentionally under certain conditions.
• You can raise built-in exceptions (like ValueError, ZeroDivisionError) or create and
raise your own custom exceptions.

Syntax: raise ExceptionType("Error message")

• ExceptionType is the type of exception you want to raise (e.g., ValueError, TypeError).
• "Error message" is a description that will help users understand what went wrong.

Example
age = int(input("Enter your age: ")) Output
Enter your age: -5
try:
if age < 0: An error occurred: Age cannot
raise ValueError("Age cannot be negative!") be negative!
else:
print(f"Your age is {age}.")
except ValueError as e:
print("An error occurred:", e)

• raise immediately stops normal flow and moves control to the nearest except block.
• It is useful for validating inputs, enforcing rules, or handling unexpected cases manually.

MULTIPLE EXCEPT BLOCKS

4. (i) Describe the use of try block and except block in python with syntax. (ii) Describe with an
example exception with arguments in python.

✓ Python allows you to have multiple except blocks for a single try block. A single try statement
can have multiple except statements to catch different types of exceptions.
✓ The except block that matches the exception generated will get executed.
✓ A try block can be associated with more than one except block to handle different exceptions.
✓ Only one handler (the first matching one) will be executed even if multiple handlers are
present.
✓ Exception handlers handle exceptions that occur only in their corresponding try block.
✓ The syntax for specifying multiple except blocks for a single try block is:

18
Important Points:
• Only one matching except block executes.
• After exception handling, normal flow resumes.
• Multiple except blocks make the program robust and able to handle different types of errors
separately.

Example :

KeyboardInterrupt:
• If the user interrupts the program (for example, by pressing Ctrl + C), the
KeyboardInterrupt exception is raised.

ValueError:
• If the user enters a non-numeric value (like "abc"), the ValueError exception is raised.
• Here, "abc" is not a number, so a ValueError occurs and its handler runs.
• After handling the exception, the program continues and prints "Bye".

MULTIPLE EXCEPTIONS IN A SINGLE BLOCK

▪ An except clause can handle multiple exceptions by listing them inside a parenthesized tuple
(Exception1, Exception2, Exception3, ...).
▪ When any one of the specified exceptions occurs, the same except block will be executed.
▪ This is useful to group related exceptions together and handle them with common code.

Syntax:
try:
# Code that may cause multiple types of exceptions
except (ExceptionType1, ExceptionType2, ExceptionType3):
# Common handling code for all listed exceptions

19
The except block mentions three exceptions together inside parentheses:

• KeyboardInterrupt → If the user interrupts the program (like pressing Ctrl + C).
• ValueError → If the user enters non-numeric data (like "abc").
• TypeError → If there’s a type mismatch.

Important rule:
→No code should be written between the try block and the except block(s).
→After try, you must immediately list all except blocks.

11. What are the built-in functions available in Python. Explain.

3. (i) Discover a program to catch a divide by zero exception. Add a finally block too. (ii) Write a
function to print the hash of any given file in Python.

MODULES
14. Explain the following: (i) Predefined Modules and (ii) User defined Modules
7. Explain python modules and packages.
Definition
• A module in Python is a file with a .py extension that contains definitions of functions and
variables.
• It enables reusability by allowing the use of functions and variables defined in one file within
other programs.

Purpose:
• Modules help to reuse one or more functions in your program, even if those functions are not
defined within the current file.
• They serve as an extension to functions by allowing the reuse of entire code blocks across
different programs.

Modules are pre-written pieces of code used to perform common tasks such as generating random
numbers, performing mathematical operations, and more.

Syntax: import module_name

✓ import is a keyword in Python used to bring in (load) a module into your program so you
can use its functions, classes, or variables.

Example
import math
print(math.sqrt(16)) # Output: 4.0
✓ This imports the math module and uses its sqrt() function to calculate the square root of
16.

PREDEFINED MODULES

✓ These are pre-installed modules that come with Python.You can use them directly by
importing.

20
Examples:
• math – for mathematical operations
• random – for generating random numbers
• datetime – for working with dates and times
• sys – for system-specific functions

i) from...import Statement
• Used to import specific items (functions/variables) from a module.
• This is useful when you don’t want the entire module, just certain parts.

Syntax: from module_name import item1, item2

Example :
from math import pi
print("PI =", pi) # Output: PI = 3.14159...

• Importing Multiple Items : To import more than one item (function or variable) from a
module by using a comma-separated list.
Syntax: from module_name import item1, item2

Example:
from math import pi, sqrt
radius = 4 Output:
area = pi * radius * radius
Area of circle: 50.26548245743669
root = sqrt(16)
Square root of 16: 4.0
print("Area of circle:", area)
print("Square root of 16:", root)

• Import All Items : imports all names (functions, variables, constants) from a module except
those whose names start with an underscore (_).
• Using as to Rename Items: The as keyword allows importing a module with an alias (a
different name). It is useful when the module name is long or confusing name.

• sys.exit() in Python
sys.exit([arg]) is used to terminate a Python program.

arg is optional:
o If arg is an integer:
▪ 0 means successful termination.
▪ Any non-zero value indicates an error or abnormal termination.
o If arg is not an integer (like a string or object), the exit code will be 1 (error).
o None is treated the same as passing 0.

The program prints "HELLO


WORLD" and then exits
21 successfully with code 0.
ii) __name__ Attribute in Python
A module is any Python file (.py) containing code (functions, variables, classes, etc.). Every module
has a built-in attribute called __name__.

Example:
# file: example.py
print("This runs always.")

if __name__ == "__main__":
print("This runs only when this file is the main module.")

Output:
This runs always.
This runs only when this file is the main module.

If imported in another file:


import example

Output:
This runs always.

(The second print does not run because it’s not the main module.)

iii) dir() Function in Python

✓ dir() is a built-in function in Python.


✓ It is used to list all the identifiers (names) defined in a module or current scope.

Identifiers include:
• Functions
• Variables
• Classes
• Other modules or objects

Example

def print_var(x): # Function definition


print(x) # Print the value of x

x = 10 # Variable assignment

22
print_var(x) # Function call with x = 10
print(dir()) # Print the list of identifiers in the current scope

Output
10
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'print_var', 'x']

Explanation:

• 10: This is printed by the print_var(x) call.


• dir() then lists all identifiers available in the current module, such as:
o Special variables: __name__, __doc__, etc.
o User-defined names: print_var, x

USER-DEFINED MODULES

• These are Python files created by the programmer to organize reusable code.
• You can import them into other programs.

Example:
Step 1: Create a module — my_module.py
# my_module.py

def display():
print("Hello")
print("Name of called module is:", __name__)

str = "Welcome to the world of Python !!!"


✓ This file is your user-defined module.
Step 2: Use the module in another Python file — main.py
# main.py

import my_module

my_module.display()
print(my_module.str)

Output of main.py:

Hello
Name of called module is: my_module
Welcome to the world of Python !!!

Output of running my_module.py directly:

$ python my_module.py
# Nothing will happen unless you explicitly call display()

You can add:


if __name__ == "__main__":
display()

23
Then the output will be:
Hello
Name of called module is: __main__

PACKAGES

✓ A package is a collection of related modules and subpackages organized in a directory


hierarchy.
✓ A module is a single Python file (.py), and a package is a directory containing a special file
called __init__.py (this file can be empty, but it signals to Python that the directory should
be treated as a package).

Structure:
my_package/

├── __init__.py

├── module1.py

└── module2.py

Importing Modules from a Package:

2 ways: import MyPackage.MyModule

from MyPackage import MyModule

Purpose of __init__.py:

• Identifies the directory as a Python package.


• Can be empty, but often contains initialization code.
• Controls what is exposed when the package is imported using from MyPackage import
*.

Example:

# module1.py

def add(a, b):


return a + b
# module2.py

def multiply(a, b):


return a * b
# __init__.py

# Initialization message
print("mypackage initialized.")

# Exposing functions at the package level


from .module1 import add
from .module2 import multiply

24
# Optional: control what's imported when using "from mypackage import *"
__all__ = ['add', 'multiply']

# main.py

# Now we can directly import add and multiply from the package
from mypackage import add, multiply

result1 = add(10, 5)
result2 = multiply(4, 3)

print("Addition Result:", result1)


print("Multiplication Result:", result2)

Output when you run main.py


mypackage initialized.
Addition Result: 15
Multiplication Result: 12

15. Write a program that validates name and age as entered by the user to determine whether the
person can cast vote or not.
def is_valid_name(name):
# Check if name contains only alphabets and is not empty
return name.isalpha()

def is_valid_age(age_str):
# Check if age is a digit and greater than or equal to 18
if age_str.isdigit():
age = int(age_str)
return age >= 18
return False

# Get user input


name = input("Enter your name: ").strip()
age_str = input("Enter your age: ").strip()

# Validate inputs
if not is_valid_name(name):
print("Invalid name. Please enter alphabetic characters only.")
elif not age_str.isdigit():
print("Invalid age. Please enter a numeric value.")
else:
age = int(age_str)
if age >= 18:
print(f"{name}, you are eligible to vote.")
else:
print(f"{name}, you are not eligible to vote. Minimum age is 18.")

25

You might also like