0% found this document useful (0 votes)
16 views15 pages

Pps Unit 3 and 4 Solution

The document provides a comprehensive overview of various Python programming concepts, including string manipulation, file handling, and functions. It includes code examples for splitting strings, using the ord() and chr() functions, reversing strings, creating and manipulating dictionaries, and performing file operations like reading, writing, and counting characters. Additionally, it covers advanced topics such as lambda functions and calculating percentages of vowels and consonants in a file.

Uploaded by

lifelessonsfz
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)
16 views15 pages

Pps Unit 3 and 4 Solution

The document provides a comprehensive overview of various Python programming concepts, including string manipulation, file handling, and functions. It includes code examples for splitting strings, using the ord() and chr() functions, reversing strings, creating and manipulating dictionaries, and performing file operations like reading, writing, and counting characters. Additionally, it covers advanced topics such as lambda functions and calculating percentages of vowels and consonants in a file.

Uploaded by

lifelessonsfz
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/ 15

UNIT 3

Q1. a) Write a program that uses split() to split a multiline string .

# Defining a multiline string

multiline_string = """Python is fun.

It is easy to learn.

It is powerful."""

# Splitting the string at each new line

lines = multiline_string.split('\n')

# Printing each line separately

print("Splitted lines are:")

for line in lines:

print(line)

kotlin

Copy

Splitted lines are:

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).

The result is a list of strings, one for each line.

The for loop prints each line individually.

b) Write a python program to understand ord() and char() function.


ans--# ord() gives ASCII value of character

char = 'A'

ascii_val = ord(char)

print(f"ASCII value of '{char}' is {ascii_val}")

# chr() gives character from ASCII value

ascii_num = 97

character = chr(ascii_num)

print(f"Character for ASCII value {ascii_num} is '{character}'")

pgsql

Copy

The ASCII value of 'A' is 65

The character for ASCII value 97 is 'a'

Definition & Explanation:

ord(char) returns the Unicode code (ASCII) of the given character.

chr(code) returns the character corresponding to the given Unicode/ASCII code.

ord() is used when converting a character to its number, and chr() is used to go back from number

to character.

c) Write a program to reverse of string by user defined function.

ans--# User-defined function to reverse a string

def reverse_string(s):

return s[::-1] # String slicing

# Taking user input

user_input = input("Enter a string to reverse: ")

reversed_str = reverse_string(user_input)

print("Reversed string:", reversed_str)

lua

Copy
Enter a string to reverse: Hello World

Reversed string: dlroW olleH

The slice notation s[::-1] creates a new string that is the reverse of s.

Reversing a string can be done by slicing or loops.

A user-defined function is a function created using the def keyword.

d) What is a function? Explain with suitable example

Definition:

A function is a reusable block of code that performs a specific task.

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):

return f"Hello, {name}!"

# Calling the function

message = greet("Alice")

print(message)

Copy

Hello, Alice!

greet is a function that takes one parameter name.

It returns a greeting message using string formatting.

The function is then called with the argument "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.

It also exits the function immediately when called.

To get values out of functions.

To use the result elsewhere (e.g., storing in variables or printing).

python

Copy

def add(a, b):

return a + b # Returns the sum

result = add(10, 20)

print("Sum is:", result)

csharp

Copy

Sum is: 30

Without return, the function would perform the operation but wouldnt pass the result back.

b) List and explain any five string methods.

ans--

Method

Description

Example

Output

upper()

Converts all letters to uppercase

"hi".upper()

'HI'

lower()
Converts all letters to lowercase

"Hi".lower()

'hi'

strip()

Removes spaces from both ends

" hi ".strip()

'hi'

replace()

Replaces substring with another

"apple".replace("a", "A")

'Apple'

find()

Finds index of first occurrence of substring

"banana".find("na")

Purpose: Converts all characters of a string to uppercase letters.

Use Case: When you want to display or compare strings in a uniform case (like user input or search

keywords).

text = "hello world"

print(text.upper()) # Output: HELLO WORLD

Purpose: Converts all characters to lowercase.

Use Case: Useful for case-insensitive comparisons or cleaning up inconsistent data.

text = "Python Is FUN"

print(text.lower()) # Output: python is fun

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

text = " Hello Python! "

cleaned = text.strip()

print(cleaned) # Output: Hello Python!

Purpose: Replaces every occurrence of a substring with another substring.

Use Case: Use it to fix typos, update keywords, or reformat data.

text = "I love Java"

updated = text.replace("Java", "Python")

print(updated) # Output: I love Python

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 @.

text = "Python programming"

print(text.find("gram")) # Output: 10

c) What is lambda or anonymous functions in python? Explain with example.

ans-- Definition:

A lambda function is a small anonymous function (i.e., without a name).

It can have any number of arguments, but only one expression.

It's often used for short tasks where defining a full function would be unnecessary.

lambda arguments: expression

Example:

# Lambda to multiply two numbers

multiply = lambda x, y: x * y

print("Product is:", multiply(4, 5))

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

str1 = input("Enter the first string: ")

str2 = input("Enter the second string for comparison: ")

# 1. Length of string

print("Length of first string:", len(str1))

# 2. Reverse of string

reversed_str = str1[::-1]

print("Reversed string:", reversed_str)

# 3. Equality check

if str1 == str2:

print("Both strings are equal.")

else:

print("Strings are not equal.")

# 4. Palindrome check

if str1 == reversed_str:

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

# 5. Substring check

substr = input("Enter a substring to search in first string: ")

if substr in str1:

print(f"'{substr}' is a substring of '{str1}'.")

else:

print(f"'{substr}' is NOT a substring of '{str1}'.")


Enter the first string: madam

Enter the second string for comparison: madam

Length of first string: 5

Reversed string: madam

Both strings are equal.

The string is a palindrome.

Enter a substring to search in first string: dam

'dam' is a substring of 'madam'.

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.

.name: name of the file

.mode: mode in which file was opened (r, w, etc.)

.closed: returns True if the file is closed, False otherwise

# Open file in read mode

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

# Print file attributes

print("File Name:", file.name)

print("File Mode:", file.mode)

print("Is File Closed:", file.closed)

# Close the file

file.close()

# Check again if file is closed

print("Is File Closed after closing:", file.closed)

Output:

File Name: example.txt

File Mode: r
Is File Closed: False

Is File Closed after closing: True

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

a value. Dictionaries are defined using curly braces {}.

# Creating a dictionary

student = {

"name": "John",

"age": 21,

"course": "Computer Science"

# Accessing an item

print("Name:", student["name"]) # Output: John

# Adding a new item

student["grade"] = "A"

# Modifying an item

student["age"] = 22

# Deleting an item

del student["course"]

# Display final dictionary

print("Updated Dictionary:", student)

Name: John

Updated Dictionary: {'name': 'John', 'age': 22, 'grade': 'A'}

A dictionary in Python stores data in key-value pairs, using curly braces {}.

You can access a value by using its key (dict["key"]) or dict.get("key").

To add a new item, assign a value to a new key: dict["new_key"] = value.


You can modify an existing key's value by reassigning it: dict["key"] = new_value.

To delete an item, use del dict["key"] or dict.pop("key").

c) Write a python program that counts the number of tabs, space and newline character in a file.

ans--# Open file in read mode

with open("sample.txt", "r") as file:

content = file.read()

# Count characters

tabs = content.count('\t')

spaces = content.count(' ')

newlines = content.count('\n')

# Print counts

print("Tabs:", tabs)

print("Spaces:", spaces)

print("Newlines:", newlines)

(Depends on the file content, assuming some dummy values)

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

be replaced with lower case.

ans--# Open the source file in read mode

with open("source.txt", "r") as source:

content = source.read()

# Apply transformations

modified_content = ""

for char in content:


if char == '.':

modified_content += ','

elif char.islower():

modified_content += char.upper()

elif char.isupper():

modified_content += char.lower()

else:

modified_content += char

# Write the modified content to the destination file

with open("destination.txt", "w") as destination:

destination.write(modified_content)

print("File copied with required transformations.")

Hello. This is a Test.

hELLO, tHIS IS A tEST,

Printed Output:

File copied with required transformations.

Q4. a) Write a python program that changes the current directory to our newly created directory.

ans--

Create a new folder (if it doesn't exist).

Change the current directory to that newly created folder.

import os

# Step 1: Create a new directory

new_dir = "NewFolder"

if not os.path.exists(new_dir): # Check if folder doesn't already exist

os.mkdir(new_dir) # Create the folder

print(f"Directory '{new_dir}' created.")

else:
print(f"Directory '{new_dir}' already exists.")

# Step 2: Change current working directory to the new folder

os.chdir(new_dir)

# Step 3: Display the current directory

print("Now we are in:", os.getcwd())

It checks if the folder NewFolder exists, if not, it creates it.

It changes the current directory to NewFolder.

It prints the current directory to confirm the change.

Directory 'NewFolder' created.

Now we are in: /path/to/NewFolder

b) Write a python program to display the contents of a file.

ans-- Explanation:

To display file contents in Python, we use the open() function with 'r' mode (read). We then read the

content using read() or readlines().

# Create a sample file first

with open("sample.txt", "w") as file:

file.write("Hello, this is a sample text file.")

# Now read and display the content

with open("sample.txt", "r") as file:

content = file.read()

print("File content:")

print(content)

Output:

File content:

Hello, this is a sample text file.

c) Describe split() in file handling with suitable example.

ans--Explanation:
The split() method, when used without any arguments, divides the string into words wherever it

encounters whitespace (spaces, newlines, or tabs).

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.

# Assume file has this line: "Python is fun"

with open("sample.txt", "r") as file:

line = file.readline()

words = line.split() # splits by space

print("Words in the line:", words)

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

consonants in the file.

Ans--

Percentage Calculation:

The percentage is calculated as:

Open and read the contents of a file.

Initialize counters for vowels, consonants, and total alphabetic characters.

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.

Display the result.

def calculate_vowels_and_consonants(file_path):

vowels = "aeiouAEIOU"

vowel_count = 0

consonant_count = 0

total_chars = 0

file = open(file_path, 'r') # Open the file


text = file.read() # Read the entire content

file.close() # Close the file

for char in text:

if char.isalpha(): # Only alphabetic characters

total_chars += 1

if char in vowels:

vowel_count += 1

else:

consonant_count += 1

# Avoid division by zero

if total_chars > 0:

vowel_percentage = (vowel_count / total_chars) * 100

consonant_percentage = (consonant_count / total_chars) * 100

print("Total alphabetic characters:", total_chars)

print("Vowels count:", vowel_count)

print("Consonants count:", consonant_count)

print("Percentage of vowels: {:.2f}%".format(vowel_percentage))

print("Percentage of consonants: {:.2f}%".format(consonant_percentage))

else:

print("No alphabetic characters found.")

# Example usage

calculate_vowels_and_consonants("sample_text.txt") # Make sure this file exists

This is a test file.

Hello World!

Total alphabetic characters: 24

Vowels count: 7

Consonants count: 17
Percentage of vowels: 29.17%

Percentage of consonants: 70.83%

PPS UNIT 3 AND 4 ANS (FCC51)

You might also like