Class Test 2 Answers
1)
Lists Tuples Sets Dictionaries
Mutability Mutable Immutable Mutable Mutable
Declaration list1 = [1, 2, 3] tuple1 = (1, 2, 3) set1 = {1, 2, 3} dict1 = {1: 'a', 2: 'b'}
Order Ordered Ordered Unordered Till 3.7 unordered, after that ordered
Duplicacy Allowed Allowed Not allowed Keys must be unique, values can repeat
# keys
for key in dict1:
print(key)
print dict[key] #values
Accessing
for item in list1: for item in tuple1: for item in set1: # values
elements
print(i) print(item) print(item) for value in [Link]():
using a loop
print(value)
# key-value pairs
for key, value in [Link]():
print(key, value)
2)
Method Description Syntax Example
txt = "hello, and welcome to my world."
Converts the first character to
capitalize() [Link]() x = [Link]()
upper case
print (x)
txt = "Hello, And Welcome To My World!"
Converts string into lower
casefold() [Link]() x = [Link]()
case
print(x)
Returns the number of times txt = "I love apples, apple are my favorite fruit"
[Link](value, start,
count() a specified value occurs in a x = [Link]("apple")
end)
string print(x)
txt = "Hello my FRIENDS"
Converts a string into lower
lower() [Link]() x = [Link]()
case
print(x)
Returns a tuple where the txt = "I could eat bananas all day"
partition() string is parted into three [Link](value) x = [Link]("bananas")
parts print(x)
Returns a string where a txt = "I like bananas"
[Link](oldvalue,
replace() specified value is replaced x = [Link]("bananas", "apples")
newvalue, count)
with a specified value print(x)
Splits the string at the txt = "welcome to the jungle"
[Link](separator,
split() specified separator, and x = [Link]()
maxsplit)
returns a list print(x)
txt = " banana "
Returns a trimmed version of
strip() [Link](characters) x = [Link]()
the string
print("of all fruits", x, "is my favorite")
Swaps cases, lower case txt = "Hello My Name Is PETER"
swapcase() becomes upper case and [Link]() x = [Link]()
vice versa print(x)
txt = "Welcome to my world"
Converts the first character of
title() [Link]() x = [Link]()
each word to upper case
print(x)
txt = "Hello my friends"
Converts a string into upper
upper() [Link]() x = [Link]()
case
print(x)
3) a)
Text files Binary files
Text files store data as a sequence of characters Binary files store data as a sequence of bytes (0s and 1s), not
(strings), typically encoded using formats like UTF-8. meant to be human-readable.
Human-readable Not human-readable
Data is handled as str in Python Data is handled as bytes in Python
Python may perform encoding/decoding automatically No automatic encoding/decoding
Line endings (\n) are interpreted Exact data is preserved (no transformation)
Examples of text files: .txt (plain text), .csv (comma Examples of binary files: Images (.jpg, .png), Audio/video files
-separated values), .json, .xml, Source code files (.py) (.mp3, .mp4), Executables (.exe), Serialized objects (.pickle)
Usage situations: Usage situations:
When working with human-readable data When working with non-text data
Logging information Images, audio, video processing
Storing structured data like CSV or JSON Storing Python objects using serialization
Configuration files When exact byte-level control is required
Example situation: Saving user input or logs Example situation: Copying an image file
b)
4) a) Solution 1:
file = open('[Link]', 'r')
# Read the entire content of the file
data = [Link]()
# Split content into words based on spaces and newlines
words = [Link]()
# Calculate the number of words
total_words = len(words)
print(f"Total number of words: {total_words}")
Solution 2:
filename = '[Link]'
with open(filename, 'r') as file:
# Read the entire content of the file
data = [Link]()
# Split content into words based on spaces and newlines
words = [Link]()
# Calculate the number of words
total_words = len(words)
print(f"Total number of words: {total_words}")
Solution 3:
# Program to count words in a text file
def count_words(filename):
try:
# Open the file in read-only mode ('r')
with open(filename, 'r') as file:
# Read the entire content of the file
data = [Link]()
# Split content into words based on spaces and newlines
words = [Link]()
# Calculate the number of words
total_words = len(words)
print(f"Total number of words: {total_words}")
except FileNotFoundError:
print("Error: The file was not found.")
# Example usage: Replace '[Link]' with your file's name
count_words('[Link]')
b) (i) abcabcabccba
(ii) 1