12 Computer Science Unit 1 Computational Thinking and Programming
12 Computer Science Unit 1 Computational Thinking and Programming
Functions
In Python, a function is a piece of code you can use repeatedly to do a specific job. It
helps make your code more organized and less repetitive. You create a function using
the def keyword, then give it a name and put any inputs (called parameters) in
1
parentheses. When you want to use the function, you "call" it, and the code inside
Page
def greet(name):
return f"Hello, {name}!"
When you call greet("Alice"), it’s like saying, “Hi, Alice!” Just think of it as creating
your custom commands that make your code do exactly what you want.
Built-in Functions: These built in functions are the ready-to-go tools in your
programming toolkit. They’re already coded and ready for you to use without
needing to do any extra work. For instance, in Python, functions like print( ) to
show stuff on your screen or len( ) to count the number of items in a list are
built-in. It’s like having a calculator where you don’t need to set up the math
formulas, they're just there, ready to go functions.
Functions Defined in Modules: Modules are like libraries or extra toolkits that you
can add to your programming environment. They come with their own set of
functions, which you can use in your projects. For example, if you’re into math, you
might use the math module in Python. Inside it, there’s a function called sqrt( ) that
helps you find the square root of a number. It’s like finding the perfect tool for a
specific job from a specialized toolbox.
User-Defined Functions: This is where you get to be excellent in your class! You
create functions to do exactly what you need. For instance, if you’re writing a game
and you want a function to check if a player has won, you can make one from
scratch. Just like baking a cake with your favorite ingredients, you decide what goes
into your function and what it does.
Creating User-Defined Function
Creating a user-defined function in Python is like designing your custom tool that fits
your exact needs. It’s a way to bundle up a set of instructions and give it a name, so
you can use it whenever you need it.
1. Define the Function: Start by using the def keyword followed by the name you
want for your function. For instance, if you want a function that adds two numbers,
you might call it add_numbers.
2. Add Parameters: Inside the parentheses, you can define the variables that your
function will use. These are called parameters. For our adding function, you’ll need
two parameters, say a and b.
3. Write the Function Body: This is where you put the code that does the actual
work. In this case, you’d write code to add the two numbers together and return the
result.
4. Call the Function: Finally, you use the function by calling it and passing the
necessary arguments (values) to it.
In this example:
Function Body: result = a + b adds the two numbers and return result sends back
the result.
Creating user-defined functions is like making your recipes or tools. They help you
repeat tasks easily without having to rewrite code. Plus, they make your code cleaner
and easier to understand—just like having a neatly organized workspace makes doing
tasks more enjoyable!
Parameters: Think of parameters as the ingredients you need for a recipe. They’re
placeholders defined in the function's definition. When you create a function, you set
up these placeholders to accept values later. For example:
1. Here, "fruit" and "liquid" are parameters. They don’t have specific values yet,
they’re just waiting to be filled in.
Arguments: Arguments are the actual values you pass into the function when you
call it. They’re like the specific ingredients you choose for your smoothie. Using
the previous example:
2. Here, "banana" and "milk" are arguments. They’re the real ingredients you’re
using in your smoothie recipe.
Parameters are like placeholders in your recipe card. They define what kind of
Page
Setting Default Values: When you define a function, you can assign default values
to some of the parameters. If you call the function without specifying a value for these
parameters, it automatically uses the default ones.
def welcome_message(name="Guest"):
print(f"Welcome, {name}!")
1. Here, name="Guest" sets "Guest" as the default value for the name parameter.
Using Default Parameters: When you call this function, you can either provide a
name or let it use the default value.
2. In the first call, the function uses the default value "Guest". In the second call, it
uses the provided argument "Alice".
Default parameters make your functions more versatile and save you from having
to repeat code. It’s a simple way to give your functions a default behavior while still
allowing for customization when needed.
Positional Parameters
Positional parameters are like the ordered slots in a function where you place your
values when calling it. They must be provided in the same order as they appear in the
function definition. Here’s a breakdown of how they work:
Defining Positional Parameters: When you create a function, you list the
parameters in a specific order. These parameters will receive the values based on
their position when the function is called.
For example, let’s define a function that takes two parameters, a and b:
Calling the Function with Positional Parameters: When you call this function,
you need to provide arguments in the same order as the parameters.
result = multiply(4, 5)
4
print(result) # Output: 20
Page
2. In this call, 4 is assigned to a, and 5 is assigned to b based on their positions.
result = multiply(5, 4)
print(result) # Output: 20
Positional parameters are straightforward and crucial for many functions because they
ensure that values are matched to the correct parts of your function. Just remember
the order of arguments matters.
Returning a Single Value: Most functions return a single value, which you can use
immediately. For example, let’s create a function that calculates the square of
a number:
def square(number):
return number * number
Here, return number * number sends back the result of the calculation.
When you call this function:
result = square(4)
print(result) # Output: 16
Returning Multiple Values: Functions can also return more than one value. This is
often done using tuples. For example, a function that returns both the sum and the
product of two numbers might look like this:
2. Here, sum_and_product( ) returns two values, which are captured in total and
product.
5
Page
Returning values from functions helps you build more flexible and powerful programs.
You can use these values to make decisions, perform further calculations, or display
results. It’s like having a function do the work and then hand you the results so you
can use them however you like.
Flow of Execution
The flow of execution in programming is like following a set of instructions step by
step. It determines the order in which statements and commands are executed in
your code. Here’s a simple breakdown of how it works:
1. Starting Point: When you run a program, the flow of execution begins at the top
of your code and proceeds line by line. This is where your program starts, just like
the first step in a recipe or a set of instructions.
print("Step 1")
print("Step 2")
print("Step 3")
Step 1
Step 2
Step 3
3. Control Flow Statements: Sometimes, you need your program to make decisions
or repeat actions. This is where control flow statements come in:
Here, the program decides which message to print based on the value of
age.
age = 18
if age >= 18:
print("You can vote.")
else:
print("You are too young to vote.")
for i in range(3):
print("This is loop iteration", i)
This loop will print the message three times, with i taking values from 0 to
2.
6
Page
Function Calls: When a function is called, the flow of execution jumps to that
function’s code, runs it, and then returns to the point where it was called. This helps
organize code and avoid repetition.
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
The program jumps to the greet function, prints the greeting, and then
continues from where it left off.
Understanding the flow of execution is crucial because it helps you predict and control
how your program behaves, ensuring it performs the right actions at the right times.
1.Global Scope: Variables defined in the global scope are accessible from anywhere
in your code, both inside and outside functions. They’re like tools you can use in
any part of your code.
2. Local Scope: Variables defined inside a function or a block of code are local to
that function or block. They can only be accessed from within the function or block
where they are defined. They’re like special tools used only for specific tasks.
Example:
def my_function():
local_var = "I am local"
print(local_var)
my_function() # Output: I am local
print(local_var) # This will raise an error
Here, local_var is defined inside my_function, so it can only be used within that
function. Trying to access it outside of my_function will result in an error because
local_var doesn’t exist in that broader scope.
Key Points:
Global Variables: Accessible everywhere in the code but can be changed from any
part of the program, which might lead to unexpected results if not managed
carefully.
Local Variables: Help manage data within specific functions or blocks, keeping
7
your code modular and less prone to errors related to variable reuse.
Page
Understanding variable scope helps you keep your code organized and
prevents issues related to variable conflicts or unintended changes.
Exception Handling
Exception handling is like having a backup plan for when things don’t go as expected
in your code. It helps you manage errors gracefully without crashing your program.
Here’s a simple introduction to how it works:
Why Use It?: Imagine you're coding a program that divides numbers. What if
someone tries to divide by zero? Without exception handling, your program might
crash. With exception handling, you can catch this error and provide a friendly
message instead.
Basic Components
Try Block: This is where you write the code that might cause an error. It’s like the
part of your program where you’re doing something risky, like accessing a file or
performing calculations.
Except Block: This catches the error if something goes wrong in the try block. It lets
you handle the error and decide what to do next, such as printing an error message
or using default values.
Finally Block (optional): This part of the code runs no matter what, whether an
error occurred or not. It’s useful for cleaning up resources, like closing files or
releasing connections.
Example:
try:
result = 10 / 0 # This will cause a division by zero error
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("This will always run.")
In this example:
Try Block: Attempts to divide by zero, which will raise an error.
Except Block: Catches the ZeroDivisionError and prints a message.
Finally Block: Runs regardless of whether an error occurred or not, ensuring any
necessary cleanup happens.
Exception handling helps keep your programs running smoothly by catching and
managing errors in a controlled way. It’s like having a safety net that allows you to
handle unexpected issues and keep your application reliable.
try Block
Purpose: You place the code that might cause an error inside the try block. This is
where you write the code that you want to execute and monitor for potential
problems.
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result is: {result}")
Here, you’re trying to convert user input into an integer and then perform
a division. If the input isn’t a valid number or is zero, it might cause an
error.
except Block
Purpose: This block catches and handles specific exceptions that occur in the try
block. You can specify different except blocks for different types of errors.
Example:
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("You can't divide by zero!")
Here, ValueError catches cases where the user input isn’t a valid number,
and ZeroDivisionError handles the case where the user enters zero,
causing a division by zero.
finally Block
Purpose: This block runs no matter what happens in the try and except blocks. It’s
typically used for clean-up actions that should occur regardless of whether an error
happened, like closing files or releasing resources.
Example:
finally:
print("This will always execute, no matter what.")
In this example, the message in the finally block will print whether or not
an exception occurred.
Complete Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result is: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("This will always execute, no matter what.")
9
Page
Key Points:
try: Executes code that might raise an exception.
except: Catches and handles specific exceptions.
finally: Executes code that should run regardless of whether an exception
occurred or not.
Using these blocks helps ensure that your program can handle errors gracefully and
complete necessary clean-up tasks, making your code more robust and reliable.
Introduction to Files
Files in programming are like containers where you store data so it can be accessed
later. They help you save and retrieve information beyond the runtime of your
program. Here’s a simple introduction to working with files:
Types of Files: Common types include text files (.txt), data files (.csv), and
code files (.py for Python scripts)
Opening a File
Purpose: To perform any operation on a file, you first need to open it. This gives
your program access to the file’s contents.
Syntax: You use the open( ) function to open a file. For example:
Here, "example.txt" is the name of the file, and "r" specifies that you want to open
it for reading. Other modes include "w" for writing, "a" for appending, and "b" for
binary files.
Reading from a File
Purpose: To access and use the data stored in a file.
Example:
This code opens a file, reads its entire content into the variable content,
prints it, and then closes the file.
Writing to a File
Purpose: To save data to a file.
Example:
This code opens a file for writing, writes the string "Hello, world!" to it, and then
closes the file. If the file already exists, it will be overwritten. If it doesn’t, it will be
10
created.
Page
Closing a File
Purpose: To ensure that changes are saved and resources are released.
Example: As shown above, always close a file using file.close( ) to ensure proper
resource management.
Using with Statement
Purpose: The with statement simplifies file handling by automatically closing the
file when done.
Example:
This code does the same thing as before but automatically handles closing the file,
even if an error occurs.
Types of Files (Text file, Binary file, CSV file)
Files come in various types, each suited for different kinds of data and uses. Here’s a
look at three common types of files: text files, binary files, and CSV files.
Text Files
Description: Text files store data in plain text format. They are easy to read and
edit using basic text editors. Each character is represented by a sequence of bytes,
usually in ASCII or UTF-8 encoding.
Usage: Ideal for storing readable content like documentation, code, or simple data.
Example Code:
Binary Files
Description: Binary files store data in a format that is not human-readable. They
can contain any type of data, including images, audio, video, and executable files.
The data is saved in binary format, which is more efficient for large data.
Usage: Used for complex data storage like multimedia files, compiled programs, and
large datasets.
Example Code:
CSV Files
Description: CSV (Comma-Separated Values) files store tabular data in a plain text
format where each line represents a row and each value is separated by a comma.
They are widely used for data exchange and storage in spreadsheets and databases.
Usage: Ideal for storing and exchanging structured data like spreadsheets or
databases.
Example Code:
import csv
# Writing to a CSV file
with open("example.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", "30", "New York"])
writer.writerow(["Bob", "25", "Los Angeles"])
# Reading from a CSV file
with open("example.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output:
['Name', 'Age', 'City']
['Alice', '30', 'New York']
['Bob', '25', 'Los Angeles']
Each file type serves different needs based on how data is represented and
used, making it important to choose the right type for your application.
Relative Paths
Definition: A relative path specifies the location of a file or directory in relation to
the current working directory (the directory from which the program is being run).
It’s like giving directions based on your current location.
Usage:Useful when you want to access files relative to the current directory or
when you move your project to a different location but keep the structure the same.
to that file.
Page
with open("files/data.txt", "r") as file:
content = file.read()
print(content)
Thispath tells the program to look for data.txt inside the files directory within the
current directory.
Absolute Paths
Definition: An absolute path specifies the full path from the root of the file system
to the desired file or directory. It’s like giving complete directions starting from a
known point, such as the root of the drive or file system.
Usage: Useful when you need to specify an exact location of a file, regardless of the
current working directory.
Example:
On a Unix-based system (like Linux or macOS), an absolute path might look like –
“/home/user/projects/files/data.txt”.
This path directs the program to look for data.txt starting from the root directory.
Key Differences
Relative Path:
Shorter and more flexible: Works well within a project or when files are moved
together.
Example: data/file.txt
Absolute Path:
Complete and specific: Always points to the exact file location regardless of the
current directory.
Understanding when to use relative versus absolute paths helps manage file locations
and access more effectively, especially when dealing with complex projects or scripts.
Text File
Opening a text file, text file open modes (r, r+, w, w+, a, a+)
Opening and managing text files in programming involves using different modes that
dictate how the file can be accessed and modified. Here’s a breakdown of how to
open text files and the various modes available:
13
To open a text file in Python, you use the open( ) function, which takes two main
arguments:
Filename: The name of the file you want to open.
Mode: A string that specifies the mode in which to open the file.
Basic Syntax:
"r" (Read):
Description: Opens the file for reading only. The file must exist; otherwise, it will
raise an error.
Usage: Use this mode when you only need to read the contents of the file.
Example:
Usage: Use this mode if you need to read from and modify the file.
Example:
"w" (Write):
Description: Opens the file for writing only. If the file already exists, it will be
truncated (cleared) before writing. If the file doesn’t exist, it will be created.
Usage: Use this mode when you want to overwrite the file’s contents or create a
new file.
Example:
with open("example.txt", "w") as file:
file.write("This is a new content.")
Description: Opens the file for both writing and reading. If the file exists, it will be
truncated before writing. If it doesn’t exist, it will be created.
Page
Usage:Use this mode when you need to both read from and write to the file, and
you want to start with a fresh file.
Example:
with open("example.txt", "w+") as file:
file.write("Initial content")
file.seek(0) # Move cursor to the beginning of the file
content = file.read()
print(content)
"a" (Append):
Description: Opens the file for appending. The file is created if it doesn’t exist.
Existing content is preserved, and new content is added at the end of the file.
Usage: Use this mode when you want to add content to the end of the file without
altering the existing content.
Example:
python
with open("example.txt", "a") as file:
file.write("Appended content.")
Usage: Use this mode when you need to read and append to a file.
Example:
with open("example.txt", "a+") as file:
file.write("More appended content.")
file.seek(0) # Move cursor to the beginning of the file
content = file.read()
print(content)
Each mode serves different needs depending on how you want to interact with the
file, whether you’re reading, writing, or both. Understanding these modes helps
ensure you use files effectively and avoid unintended data loss or corruption.
Data Integrity: Ensures that any data written to the file is properly saved and not
Page
lost.
How to Close a File: You use the close( ) method of the file object to close the file.
Example:
How It Works:
The with statement creates a context for the file operation. Once the block inside the
statement is exited, the file is automatically closed.
Example:
In this example:
When you use open("example.txt", "w") as a file, the file is opened for writing.
After the block of code inside the with statement completes, the file is automatically
closed.
Similarly, with open("example.txt", "r") as a file opens the file for reading, and it
will be closed automatically after reading the content.
Advantages of Using With
Automatic Closing: Ensures the file is closed properly, reducing the risk of file
corruption or resource leaks.
Exception Handling: Even if an error occurs within the block, the file is still closed
properly.
Cleaner Code: Reduces the amount of code needed to manage file operations.
Using the with statement is a more Pythonic way to handle files, making your code
safer and more readable.
Usage: Use write( ) when you need to write a single string or data chunk to a file.
Example:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a new line.")
In this example:
The write( ) method writes "Hello, world!\n" to the file, followed by "This is a
new line.".
Example:
# Appending to a file
with open("example.txt", "a") as file:
file.write("\nAdding a new line at the end.")
In this example:
The new line "Adding a new line at the end." is added to the end of the file without
modifying existing content.
Writing Multiple Lines with writelines( )
Description: The writelines( ) method writes a list of strings to a file. Each string in
the list is written as-is without additional new lines between them, so you need to
include \n in the strings if you want line breaks.
Usage: Use writelines( ) when you have multiple lines of text and want to write
them all at once.
Example:
In this example:
The writelines( ) method writes each string in the lines list to the file, preserving
the line breaks defined in the strings.
17
Key Differences
write( ):
Page
writelines( ):
o Writes a list of strings to the file.
o No automatic line breaks between entries; include \n in each string if
needed.
o Typically used in write mode.
Using read( )
Description: The read( ) method reads the entire content of a file and returns it as
a string. This method is useful when you want to load the whole file content at once.
Usage: Typically used when you need to read the entire file, especially if the file size
is manageable and fits into memory.
Basic Example
Explanation:
Example:
Explanation:
file.read(10): Reads up to 10 characters from the file.
18
If you call read( ) multiple times, it continues reading from where it left off.
Example:
Explanation:
file.read(5): Reads the first 5 characters.
file.read(5): Reads the next 5 characters, starting where the last read left off.
Important Points
End-of-File: When read( ) reaches the end of the file, it returns an empty string.
FileHandling: Always use with to open files. It ensures the file is properly closed
after operations, even if an error occurs.
Memory Considerations: If dealing with very large files, consider using other
methods like readline( ) or iterating over the file object to avoid loading the entire
file into memory at once.
Using read( ) is straightforward for accessing the full content of a text file and is
handy when you need to work with the entire file data as a single string.
readline( )
Description: The readline( ) method reads one line from the file at a time. It reads
until it encounters a newline character (\n) or the end of the file.
Usage: Use readline( ) when you want to read a file line by line and process each
line individually.
Example:
Explanation:
file.readline( ): Reads the next line from the file.
while line: Continues reading until the end of the file is reached (when readline( )
19
Usage: Use readlines( ) when you want to read the entire file into memory and
work with each line as a list element.
Example:
Explanation:
file.readlines( ): Reads all lines and returns them as a list.
for line in lines: Iterates through each line in the list and prints it.
Key Differences
readline( ):
Reads One Line at a Time: Useful for processing files line by line without loading
the entire file into memory.
Memory Efficient: Ideal for very large files or when you only need to read a specific
part of the file.
readlines( ):
Reads All Lines at Once: Loads the entire file into memory as a list of lines.
Convenient for Small to Medium Files: Useful when you need to work with all
lines at once or when you need to perform operations on the entire file content.
Choosing Between readline( ) and readlines( )
seek( )
20
Description: The seek( ) method is used to move the file cursor to a specific
position in the file. This is useful when you want to read or write data from a
Page
particular location.
Usage: Commonly used to reposition the cursor for reading or writing data,
especially after partial reads or writes.
Syntax:
python
file.seek(offset, whence)
offset: The position (in bytes) to move the cursor to, relative to the position specified
by whence.
Examples:
Move to the Beginning of the File:
tell( )
Description: The tell( ) method returns the current position of the file cursor. This
is useful for tracking where you are in the file or for debugging purposes.
Usage: Often used after seek( ) to confirm the cursor position or to determine how
far you’ve read into the file.
Syntax:
python
position = file.tell()
21
Example:
Page
with open("example.txt", "r") as file:
file.seek(10) # Move cursor to the 10th byte
position = file.tell() # Get current cursor position
print(f"Current position: {position}")
Manipulation of Data in a Text File
Manipulating data in a text file involves various operations such as reading,
modifying, and writing data at specific positions. Here’s a more detailed look at how
you can perform these operations using Python:
1. Reading Data
To work with data in a file, you first need to read it. Depending on your needs, you can
read the entire file, specific lines, or chunks of data.
Example:
with open("example.txt", "r") as file:
content = file.read() # Read the entire file content
print(content)
2. Writing Data
You can write data to a file in different modes ("w", "a", "r+") based on whether you
want to overwrite, append, or modify existing content.
Examples:
Overwrite Existing Content:
with open("example.txt", "w") as file:
file.write("New content\n")
Append to Existing Content
with open("example.txt", "a") as file:
file.write("Appended content\n")
3. Inserting Data at a Specific Position
To insert data at a specific location in a file, you need to read the existing content,
modify it, and then write it back. This is because text files don’t support direct
insertion; you must rewrite the file with the new content.
Steps:
1. Read the Content: Load the file content into memory.
2. Modify the Content: Insert or modify the content as needed.
3. Write the Modified Content: Write the modified content back to the file.
Example:
Python
1
# Insert data at a specific position
2
with open("example.txt", "r+") as file:
3
content = file.read() # Read the entire file content
4
22
10
# Write the new content
11
file.write(new_content)
12
13
# Optional: Write the remaining content if needed
14
remaining_content = file.read()
15
file.seek(insert_position) # Move cursor back to insert position
16
file.write(new_content + remaining_content)
4. Truncating Data
Truncating a file means cutting off its content from a specified position. This is useful
for removing unwanted content from the end of a file.
Example:
with open("example.txt", "r+") as file:
file.seek(10) # Move cursor to the 10th byte
file.truncate() # Remove everything from the 10th byte onwards
5. Replacing Data
To replace a portion of the file, you typically read the entire file, modify the specific
part, and then write the entire modified content back to the file.
Example:
Python
1
with open("example.txt", "r+") as file:
2
content = file.read() # Read the entire file content
3
23
content = content.replace("old text", "new text") # Replace old text with new text
Page
4
file.seek(0) # Move cursor to the beginning
5
file.write(content) # Write the modified content
6
file.truncate() # Ensure file is truncated to the new length
Binary file
Basic operations on a binary file
Binary files are files that contain data in a format that is not human-readable, as
opposed to text files which contain data in plain text. In Python, you can perform
various operations on binary files, including reading and writing data. Here’s a guide
on how to work with binary files:
Basic Operations on Binary Files
1. Opening a Binary File
To work with binary files, you need to open them in binary mode. This is done by
adding a "b" to the mode string ("rb" for reading, "wb" for writing, "ab" for appending,
etc.).
Example:
# Open a binary file for reading
with open("example.bin", "rb") as file:
data = file.read() # Read the entire file content
print(data)
2. Reading from a Binary File
You can read binary data in chunks or as a whole. Binary files are typically read in
bytes, so methods like read(), read(size), and readinto() can be used.
Read the Entire File:
with open("example.bin", "rb") as file:
data = file.read() # Read the entire file
Read a Specific Number of Bytes:
with open("example.bin", "rb") as file:
chunk = file.read(10) # Read the first 10 bytes
Read Line by Line: For binary files, this is less common, but you can read data into
memory and then process it as needed.
3. Writing to a Binary File
To write binary data, open the file in binary write mode ("wb") or append mode ("ab").
Data should be in bytes format.
Examples:
Write Data:
with open("example.bin", "wb") as file:
data = b'\x00\x01\x02\x03' # Binary data to write
file.write(data)
Append Data:
with open("example.bin", "ab") as file:
additional_data = b'\x04\x05\x06'
file.write(additional_data)
4. Seek and Tell
You can use seek() to move the file cursor and tell() to get the current position of the
cursor.
Seek:
with open("example.bin", "rb") as file:
24
Tell:
with open("example.bin", "rb") as file:
file.seek(10) # Move cursor to the 10th byte
position = file.tell() # Get the current position (should be 10)
5. Truncating a Binary File
Truncate the file to reduce its size or remove data from a specific point. This can be
done using the truncate() method.
Example:
with open("example.bin", "r+b") as file:
file.seek(10) # Move cursor to the 10th byte
file.truncate() # Truncate the file from the 10th byte onward
Open Using File Open Modes (rb, rb+, wb, wb+, ab, ab+)
When working with binary files in Python, you can use various file open modes to
control how you read, write, and append data. Each mode serves a different purpose
and affects how the file is handled. Here’s a breakdown of the file open modes
for binary files:
File Open Modes for Binary Files
"rb" (Read Binary)
Description: Opens a file for reading in binary mode.
Usage: Use this mode when you only need to read data from the file and do not
need to modify it.
Example:
with open("example.bin", "rb") as file:
data = file.read() # Read the entire binary content
"rb+" (Read and Write Binary)
Description: Opens a file for both reading and writing in binary mode.
Usage: Use this mode when you need to read from and write to the same file.
The file must exist; if it doesn’t, an error will occur.
Example:
with open("example.bin", "rb+") as file:
data = file.read(10) # Read the first 10 bytes
file.seek(0) # Move cursor to the start
file.write(b'\x01\x02\x03') # Write binary data
"wb" (Write Binary)
Description: Opens a file for writing in binary mode. If the file already exists, it
will be truncated (i.e., overwritten). If the file does not exist, a new file will be
created.
Usage: Use this mode when you need to create a new file or overwrite an
existing file with binary data.
Example:
with open("example.bin", "wb") as file:
file.write(b'\x01\x02\x03\x04') # Write binary data
"wb+" (Write and Read Binary)
Description: Opens a file for both writing and reading in binary mode. If the file
exists, it will be truncated. If the file does not exist, a new file will be created.
Usage: Use this mode when you need to both read and write data, and you
don’t mind overwriting the existing file content or creating a new file.
Example:
with open("example.bin", "wb+") as file:
file.write(b'\x01\x02\x03') # Write binary data
file.seek(0) # Move cursor to the start
25
Description: Opens a file for appending in binary mode. Data is written at the
end of the file. If the file does not exist, a new file will be created.
Usage: Use this mode when you need to add data to the end of an existing file
without modifying the existing content.
Example:
with open("example.bin", "ab") as file:
file.write(b'\x05\x06\x07') # Append binary data
"ab+" (Append and Read Binary)
Description: Opens a file for both appending and reading in binary mode. Data
is written at the end of the file, and you can also read from any part of the file. If
the file does not exist, a new file will be created.
Usage: Use this mode when you need to both append data to the end of a file
and read from it.
Example:
with open("example.bin", "ab+") as file:
file.write(b'\x08\x09\x0A') # Append binary data
file.seek(0) # Move cursor to the start
data = file.read() # Read the entire content
Close a Binary File
Closing a binary file in Python is essential to ensure that all data is properly written to
the file and that system resources are released. The close() method is used to close a
file after you are done with it. Here’s how you can manage closing binary files:
Closing a Binary File
Using close() Method
After performing operations on a file, you should explicitly call the close() method to
close the file. This is important for ensuring that all changes are saved and resources
are freed.
Example:
file = open("example.bin", "wb") # Open file in write-binary mode
file.write(b'\x01\x02\x03\x04') # Write binary data
file.close() # Close the file
Explanation:
file = open("example.bin", "wb"): Opens the file in write-binary mode.
file.write(b'\x01\x02\x03\x04'): Writes binary data to the file.
file.close(): Closes the file, ensuring that all data is saved and system
resources are released.
Using with Statement (Preferred Approach)
The with statement is the preferred way to work with files because it automatically
handles opening and closing the file. When the block of code inside the with
statement is exited, the file is closed automatically, even if an error occurs.
Example:
with open("example.bin", "wb") as file: # Open file in write-binary
mode
file.write(b'\x01\x02\x03\x04') # Write binary data
# File is automatically closed here
Explanation:
with open("example.bin", "wb") as file:: Opens the file in write-binary mode
and assigns it to the variable file.
file.write(b'\x01\x02\x03\x04'): Writes binary data to the file.
No need to call file.close(): The file is automatically closed when the block
inside the with statement is exited.
Why Closing a File is Important
26
Data Integrity: Ensures that all written data is properly saved to the file. If a
file is not closed, some data might not be written.
Page
Resource Management: Releases system resources (like file handles) that are
used when a file is open. Not closing a file can lead to resource leaks.
Avoids Errors: Prevents potential file access errors or corruption.
Import pickle module, dump() and load() method
The pickle module in Python is used for serializing and deserializing Python objects,
which means converting Python objects to a byte stream (serialization) and
converting byte streams back into Python objects (deserialization). This is particularly
useful for saving and loading complex data structures to and from files. The dump()
and load() methods are key functions in this process.
Importing the pickle Module
Before using pickle, you need to import it:
import pickle
pickle.dump()
The dump() method is used to serialize a Python object and write it to a file.
Syntax:
pickle.dump(obj, file, protocol=None)
obj: The Python object you want to serialize (e.g., a list, dictionary, custom
object).
file: A file-like object (e.g., an opened file) where the serialized data will be
written.
protocol: Optional. The protocol version to use for serialization. If omitted, the
default protocol is used.
Example:
import pickle
data = {'name': 'Alice', 'age': 25, 'is_student': True}
with open('data.pkl', 'wb') as file: # Open file in binary write mode
pickle.dump(data, file) # Serialize `data` and write to the file
Explanation:
data: The Python object to be serialized.
with open('data.pkl', 'wb') as file: Opens a file in binary write mode.
pickle.dump(data, file): Serializes the data object and writes it to the file.
pickle.load()
The load() method is used to deserialize a Python object from a file, essentially
reading the byte stream and converting it back into a Python object.
Syntax:
python
obj = pickle.load(file)
file: A file-like object (e.g., opened file) containing the serialized data.
Returns: The deserialized Python object.
Example:
import pickle
with open('data.pkl', 'rb') as file: # Open file in binary read mode
data = pickle.load(file) # Deserialize data from the file
print(data) # Output: {'name': 'Alice', 'age': 25, 'is_student': True}
Explanation:
with open('data.pkl', 'rb') as file: Opens a file in binary read mode.
pickle.load(file): Reads the serialized data from the file and deserializes it
back into a Python object.
Read, write/create, search, append, and update Operations in a Binary File
Handling binary files involves various operations such as reading, writing, searching,
appending, and updating data. Here’s a guide on how to perform these operations in
binary files using Python:
27
1
with open("example.bin", "rb") as file:
2
data = file.read()
3
if b'\x02\x03' in data:
4
print("Pattern found!")
5
else:
6
print("Pattern not found.")
4. Appending to a Binary File
To append data to a binary file, open the file in binary append mode ("ab"). This mode
adds data to the end of the file without modifying existing content.
Append Data:
with open("example.bin", "ab") as file:
file.write(b'\x05\x06\x07') # Append binary data
5. Updating Data in a Binary File
28
Updating data involves reading the existing content, modifying it, and then writing it
back to the file. This generally requires reading the entire file, making changes, and
Page
1
with open("example.bin", "rb+") as file:
2
data = file.read() # Read all data
3
new_data = data.replace(b'\x02', b'\x99') # Replace specific bytes
4
file.seek(0) # Move cursor to the start
5
file.write(new_data) # Write modified data
6
file.truncate() # Truncate file to the new length
CSV file
Import csv module, open/close CSV file
CSV (Comma-Separated Values) files are a popular format for storing tabular data.
The csv module in Python provides functions to work with CSV files, allowing you to
read from and write to them efficiently. Here’s a guide on how to use the csv module
to handle CSV files:
Importing the csv Module
Before you can work with CSV files, you need to import the csv module:
import csv
Opening and Closing a CSV File
To work with CSV files, you need to open them, perform the necessary operations,
and then close them. Python's csv module works with file objects, so you use standard
file-handling methods to open and close files.
1. Opening a CSV File
You open a CSV file using Python's built-in open() function and pass the file object to
the csv module's reader or writer functions.
Example: Opening a CSV File for Reading
import csv
with open('data.csv', mode='r', newline='') as file: # Open file in read mode
reader = csv.reader(file) # Create a CSV reader object
for row in reader:
print(row) # Print each row in the CSV file
Example: Opening a CSV File for Writing
import csv
with open('data.csv', mode='w', newline='') as file: # Open file in
write mode
writer = csv.writer(file) # Create a CSV writer object
writer.writerow(['Name', 'Age', 'City']) # Write header row
29
rows = [
['Name', 'Age', 'City'], # Header row
['Alice', '30', 'New York'], # Data row
['Bob', '25', 'Los Angeles'], # Another data row
['Charlie', '35', 'Chicago'] #Another data row]
writer.writerows(rows) # Write all rows at once
Explanation:
csv.writer(file): Creates a writer object.
rows: A list of lists, where each inner list represents a row.
writer.writerows(rows): Writes all rows to the file at once.
Handling Newlines
When opening a CSV file, use newline='' in the open() function to handle newline
characters correctly and avoid blank lines between rows.
Read from a csv file using reader()
Reading data from a CSV file in Python using the csv module involves using the
csv.reader() function. This function creates a reader object that iterates over lines in
the CSV file, providing each row as a list of strings. Here's a detailed guide on how to
read from a CSV file:
Importing the csv Module
First, you need to import the csv module:
import csv
Reading from a CSV File
1. Reading All Rows
You can read all rows from a CSV file using the csv.reader() object in a loop. Each row
is returned as a list of strings.
Example:
import csv
# Open file in read mode
with open('data.csv', mode='r', newline='') as file:
reader = csv.reader(file) # Create a CSV reader object
# Iterate over rows in the CSV file
for row in reader:
print(row) # Print each row (list of strings)
Explanation:
csv.reader(file): Creates a reader object to read the CSV file.
for row in reader: Iterates through each row in the file.
print(row): Prints the current row as a list of strings.
2. Reading Specific Rows
If you want to read only specific rows or perform operations on certain rows, you can
do so by iterating through the rows and adding conditional logic.
Example:
import csv
# Open file in read mode
with open('data.csv', mode='r', newline='') as file:
reader = csv.reader(file) # Create a CSV reader object
# Read and print only rows where the age is greater than 30
for row in reader:
if row[1].isdigit() and int(row[1]) > 30: # Check if the age
(second column) is greater than 30
print(row)
Explanation:
row[1].isdigit(): Checks if the value in the second column is a digit before
31
converting it to an integer.
int(row[1]) > 30: Filters rows where the age is greater than 30.
Page
Data Structure
A data structure is a way of organizing and storing data so that it can be used efficiently. It helps
in managing large amounts of data and performing different operations like searching, sorting,
and modifying data. Examples of data structures include arrays, linked lists, stacks, and queues.
They are essential for writing good programs and solving complex problems.
Stack, operations on stack (push & pop)
A stack is a fundamental data structure used in computer science, known for its Last In, First
Out (LIFO) principle. This means that the last element added to the stack will be the first one to
be removed. Think of a stack like a stack of plates: you add and remove plates from the
top.
Stack Operations
The primary operations for a stack are:
1. Push: Add an item to the top of the stack.
2. Pop: Remove the item from the top of the stack.
3. Peek/Top: View the item at the top of the stack without removing it (optional, but
commonly used).
4. IsEmpty: Check if the stack is empty (optional, but useful for checking stack status).
Implementing a Stack
You can implement a stack using various programming languages and approaches. Here’s how
you can do it in Python using a list:
1. Push Operation
The push operation adds an item to the top of the stack. In Python, you can use the append()
method of a list to simulate this.
Example:
stack = [] # Initialize an empty stack
# Push items onto the stack
stack.append(1)
stack.append(2)
stack.append(3)
print(stack) # Output: [1, 2, 3]
Explanation:
stack.append(1): Adds 1 to the top of the stack.
stack.append(2): Adds 2 to the top of the stack.
stack.append(3): Adds 3 to the top of the stack.
2. Pop Operation
The pop operation removes the item from the top of the stack. You can use the pop() method of
a list to perform this operation.
32
Example:
stack = [1, 2, 3] # Stack with elements
Page
1
class Stack:
2
def __init__(self):
3
33
6
def push(self, item):
7
"""Add an item to the top of the stack."""
8
self.stack.append(item) # Use list append method to push item
9
10
11
def pop(self):
12
"""Remove and return the item from the top of the stack."""
13
if not self.is_empty():
14
return self.stack.pop() # Use list pop method to remove and return top item
15
else:
16
raise IndexError("pop from an empty stack") # Raise an exception if stack is
empty
17
18
19
def peek(self):
20
"""Return the item at the top of the stack without removing it."""
21
if not self.is_empty():
22
return self.stack[-1] # Access the last item in the list
23
else:
34
24
Page
26
27
def is_empty(self):
28
"""Check if the stack is empty."""
29
return len(self.stack) == 0 # Return True if the stack is empty
30
31
32
def __str__(self):
33
"""Return a string representation of the stack."""
34
return str(self.stack) # Return list as string for easy visualization
35
36
37
# Example usage
38
if __name__ == "__main__":
39
my_stack = Stack()
40
41
# Push elements
42
my_stack.push(10)
43
my_stack.push(20)
44
35
my_stack.push(30)
Page
45
46
print("Stack after pushes:", my_stack)
47
# Peek the top element
48
print("Top element:", my_stack.peek())
49
50
# Pop elements
51
print("Popped element:", my_stack.pop())
52
print("Stack after pop:", my_stack)
53
54
# Check if the stack is empty
55
print("Is stack empty?", my_stack.is_empty())
Explanation
__init__(): Initializes an empty list to hold stack elements.
push(item): Adds an item to the top of the stack using append().
pop(): Removes and returns the top item using pop(). Raises an IndexError if the stack is
empty.
peek(): Returns the top item without removing it. Raises an IndexError if the stack is
empty.
is_empty(): Returns True if the stack is empty, otherwise False.
__str__(): Provides a string representation of the stack for easy printing.
Usage
Push: my_stack.push(10) adds 10 to the stack.
Peek: my_stack.peek() returns 30, the top item.
Pop: my_stack.pop() removes and returns 30.
Is Empty: my_stack.is_empty() returns False if the stack is not empty.
This implementation leverages Python's list operations to efficiently manage stack functionality
while ensuring that common stack-related errors are handled.
37
Page