Pps Unit 3 and 4 Solution
Pps Unit 3 and 4 Solution
It is easy to learn.
It is powerful."""
lines = multiline_string.split('\n')
print(line)
kotlin
Copy
Python is fun.
It is easy to learn.
It is powerful.
split() is a Python string method used to divide a string into a list based on a specified delimiter (by
default, whitespace).
A multiline string is a string that spans multiple lines, created using triple quotes (''' or """)
Explanation:
The triple quotes allow you to write the string across multiple lines.
split('\n') tells Python to break the string wherever it finds a newline character (\n).
char = 'A'
ascii_val = ord(char)
ascii_num = 97
character = chr(ascii_num)
pgsql
Copy
ord() is used when converting a character to its number, and chr() is used to go back from number
to character.
def reverse_string(s):
reversed_str = reverse_string(user_input)
lua
Copy
Enter a string to reverse: Hello World
The slice notation s[::-1] creates a new string that is the reverse of s.
Definition:
Functions help make programs modular, more readable, and easier to debug.
python
Copy
def function_name(parameters):
# code block
return result
python
Copy
def greet(name):
message = greet("Alice")
print(message)
Copy
Hello, Alice!
Functions can also be called multiple times with different inputs, making them extremely powerful.
Q2. a) Write a note on return statement with example.
ans-- Definition:
The return statement is used inside a function to send back a result (value) to the function caller.
python
Copy
csharp
Copy
Sum is: 30
Without return, the function would perform the operation but wouldnt pass the result back.
ans--
Method
Description
Example
Output
upper()
"hi".upper()
'HI'
lower()
Converts all letters to lowercase
"Hi".lower()
'hi'
strip()
" hi ".strip()
'hi'
replace()
"apple".replace("a", "A")
'Apple'
find()
"banana".find("na")
Use Case: When you want to display or compare strings in a uniform case (like user input or search
keywords).
Purpose: Removes any leading and trailing spaces or special whitespace characters like tabs or
newlines.
Use Case: Perfect for cleaning user input or strings loaded from files.
python
Copy
cleaned = text.strip()
Purpose: Finds the first index of a specified substring. Returns -1 if not found.
Use Case: Helps in searching or parsing strings, such as checking if an email contains @.
print(text.find("gram")) # Output: 10
ans-- Definition:
It's often used for short tasks where defining a full function would be unnecessary.
Example:
multiply = lambda x, y: x * y
Product is: 20
Lambda functions are often used with map(), filter(), and sorted().
d) Write a python program that accepts a string from user and perform following string operations-
i. Calculate length of string ii. String reversal iii. Equality check of two strings iii. Check palindrome ii.
Check substring.
Ans--
# Accepting input
# 1. Length of string
# 2. Reverse of string
reversed_str = str1[::-1]
# 3. Equality check
if str1 == str2:
else:
# 4. Palindrome check
if str1 == reversed_str:
else:
# 5. Substring check
if substr in str1:
else:
A palindrome is a word that reads the same forward and backward (like "madam", "level").
UNIT4
Q3. a) Write a program to open a file and print its attribute values.
file.close()
Output:
File Mode: r
Is File Closed: False
b) Explain creating a dictionary. How to access, add, modify and delete items in dictionary.
ans--Definition:
A dictionary in Python is an unordered collection of items. Each item is a pair consisting of a key and
# Creating a dictionary
student = {
"name": "John",
"age": 21,
# Accessing an item
student["grade"] = "A"
# Modifying an item
student["age"] = 22
# Deleting an item
del student["course"]
Name: John
A dictionary in Python stores data in key-value pairs, using curly braces {}.
c) Write a python program that counts the number of tabs, space and newline character in a file.
content = file.read()
# Count characters
tabs = content.count('\t')
newlines = content.count('\n')
# Print counts
print("Tabs:", tabs)
print("Spaces:", spaces)
print("Newlines:", newlines)
output-Tabs: 3
Spaces: 15
Newlines: 5
d) Write a python program to copy contents of one file to another. While copying a) all full stops are
to be replaced with commas b) lower case are to be replaced with upper case c) upper case are to
content = source.read()
# Apply transformations
modified_content = ""
modified_content += ','
elif char.islower():
modified_content += char.upper()
elif char.isupper():
modified_content += char.lower()
else:
modified_content += char
destination.write(modified_content)
Printed Output:
Q4. a) Write a python program that changes the current directory to our newly created directory.
ans--
import os
new_dir = "NewFolder"
else:
print(f"Directory '{new_dir}' already exists.")
os.chdir(new_dir)
ans-- Explanation:
To display file contents in Python, we use the open() function with 'r' mode (read). We then read the
content = file.read()
print("File content:")
print(content)
Output:
File content:
ans--Explanation:
The split() method, when used without any arguments, divides the string into words wherever it
Each line in the file is read, and the words in each line are extracted into a list of words.
The method returns a list where each word in the line is a separate element.
line = file.readline()
Words in the line: ['Hello,', 'this', 'is', 'a', 'sample', 'text', 'file.']
d) Write a python program that reads data from a file and calculates the percentage of vowels and
Ans--
Percentage Calculation:
Loop through each character in the file, check if it is a vowel or consonant, and update the counters
accordingly.
After processing the file, calculate the percentage of vowels and consonants.
def calculate_vowels_and_consonants(file_path):
vowels = "aeiouAEIOU"
vowel_count = 0
consonant_count = 0
total_chars = 0
total_chars += 1
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
if total_chars > 0:
else:
# Example usage
Hello World!
Vowels count: 7
Consonants count: 17
Percentage of vowels: 29.17%