Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

python

The document explains various Python concepts including string manipulation methods like join() and split(), file handling techniques, and the use of assertions. It also covers file compression, operator overloading, and polymorphism with practical examples. Additionally, it provides code snippets for functions like DivExp, methods for copying files, and creating a backup of a folder into a ZIP file.

Uploaded by

iampanthera1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

python

The document explains various Python concepts including string manipulation methods like join() and split(), file handling techniques, and the use of assertions. It also covers file compression, operator overloading, and polymorphism with practical examples. Additionally, it provides code snippets for functions like DivExp, methods for copying files, and creating a backup of a folder into a ZIP file.

Uploaded by

iampanthera1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1.

Explain the following:

o (i) join() method: The join() method in Python is used to concatenate elements of a
list or tuple into a single string, with a specified delimiter between each element.
For example:

python

my_list = ['apple', 'banana', 'cherry']

result = ','.join(my_list)

print(result) # Output: apple,banana,cherry

o (ii) split() method: The split() method splits a string into a list where each word is a
list item. By default, it splits by whitespace, but you can specify a delimiter.
Example:

python

my_string = "apple,banana,cherry"

result = my_string.split(',')

print(result) # Output: ['apple', 'banana', 'cherry']

2. Illustrate the benefits of compressing file? Also explain reading of a zip file with an
example.

o Benefits of compressing files: Compression reduces file size which saves storage
space and speeds up file transfer over networks. It also can make data more
manageable and easier to archive.

o Reading a zip file: You can use Python's zipfile module to read zip files. Here's an
example:

python

import zipfile

with zipfile.ZipFile('example.zip', 'r') as zip_ref:

zip_ref.extractall('extracted_folder')

This example extracts all contents of 'example.zip' to a folder named 'extracted_folder'.

3. Explain the concept of File Handling. Also explain the reading & writing process with
suitable example.

o File Handling: File handling in Python involves opening, reading, writing, and
closing files.
o Reading & Writing Example:

python

# Writing to a file

with open('example.txt', 'w') as file:

file.write('Hello, World!')

# Reading from a file

with open('example.txt', 'r') as file:

content = file.read()

print(content) # Output: Hello, World!

4. Briefly explain Assertions and raise an exception.

o Assertions: Assertions in Python are used to check if a condition is true, and if not,
it raises an AssertionError. They are useful for debugging:

python

def divide(a, b):

assert b != 0, "Cannot divide by zero"

return a / b

# This will raise an AssertionError

divide(10, 0)

5. With the code snippet, give the di erence between shutil.copy() and shutil.copytree()
method.

o shutil.copy() copies a single file from source to destination.

o shutil.copytree() copies an entire directory tree from source to destination.


Example:

python

import shutil

# Copying a single file

shutil.copy('source.txt', 'destination.txt')
# Copying a directory

shutil.copytree('source_folder', 'destination_folder')

6. Explain the concept of the following with examples.

o (i) Operator Overloading: This allows you to define how Python operators work with
your own classes. Example:

python

class Vector:

def __init__(self, x, y):

self.x = x

self.y = y

def __add__(self, other):

return Vector(self.x + other.x, self.y + other.y)

v1 = Vector(2, 3)

v2 = Vector(4, 5)

v3 = v1 + v2

print(f"Vector({v3.x}, {v3.y})") # Output: Vector(6, 8)

o (ii) Type based Dispatch: This involves di erent behavior based on the type of
object. Python does this automatically with polymorphism. Example:

python

def add(a, b):

return a + b

print(add(1, 2)) # Output: 3 (integers)

print(add("Hello", "World")) # Output: HelloWorld (strings)

7. Write a function named DivExp which takes TWO parameters a, b and returns a value c
(=a/b). Write suitable assert for a>0 in function DivExp and raise an exception for when
b>0. Develop a suitable program which reads two values from the console and calls a
function DivExp.

python

def DivExp(a, b):

assert a > 0, "a must be greater than 0"

if b > 0:

raise ValueError("b must be less than or equal to 0")

return a / b

try:

a = float(input("Enter value for a: "))

b = float(input("Enter value for b: "))

result = DivExp(a, b)

print(f"Result: {result}")

except AssertionError as e:

print(f"Assertion Error: {e}")

except ValueError as e:

print(f"Value Error: {e}")

except ZeroDivisionError:

print("Cannot divide by zero")

8. Explain the methods init and str, with suitable example to each.

o __init__: Constructor method used to initialize new objects. Example:

python

class Car:

def __init__(self, make, model):

self.make = make

self.model = model

my_car = Car("Toyota", "Corolla")


print(f"My car is a {my_car.make} {my_car.model}")

o __str__: Returns a string representation of the object. Example:

python

class Car:

def __init__(self, make, model):

self.make = make

self.model = model

def __str__(self):

return f"{self.make} {self.model}"

my_car = Car("Toyota", "Corolla")

print(my_car) # Output: Toyota Corolla

9. Interpret the steps involved in adding Bullets to Wiki-Markup-support with appropriate


code.

o Adding bullets in Wiki-Markup typically involves using asterisks *. Here's how you
might simulate this in Python:

python

def wiki_bullet(text):

lines = text.split('\n')

bulleted_lines = ['* ' + line for line in lines]

return '\n'.join(bulleted_lines)

text = "First line\nSecond line\nThird line"

print(wiki_bullet(text))

This function adds a bullet (*) to the beginning of each line in the given text.

10. With a suitable code snippet, explain Assertions and the contents of an assert
statement.

python

def check_positive(x):

assert x > 0, "x must be positive"


return x

try:

result = check_positive(-1)

except AssertionError as e:

print(e) # Output: x must be positive

11. Interpret for Opening of a file with open() functions, reading the contents of the file
with read() & writing to files with write().

python

# Opening, reading, and writing to files

with open('example.txt', 'w') as file:

file.write('This is a test.')

with open('example.txt', 'r') as file:

content = file.read()

print(content) # Output: This is a test.

with open('example.txt', 'a') as file:

file.write('\nThis is appended.')

12. Interpret on how you copy files & folders using shutil module.

o See the explanation under question 5 for shutil.copy() and shutil.copytree().

13. Develop a program to Back Up a given Folder (Folder in a current working directory) into
a ZIP File by using relevant modules and suitable methods.

python

import os

import zipfile

def backup_to_zip(folder_name, output_filename):

with zipfile.ZipFile(output_filename, 'w') as zipf:


for foldername, subfolders, filenames in os.walk(folder_name):

for filename in filenames:

file_path = os.path.join(foldername, filename)

zipf.write(file_path)

backup_to_zip('my_folder', 'backup.zip')

14. With an example, explain the following in python.

o i. Defining a class:

python

class Dog:

def __init__(self, name):

self.name = name

def bark(self):

return f"{self.name} says Woof!"

o ii. initiating a class:

python

my_dog = Dog('Rex')

print(my_dog.bark()) # Output: Rex says Woof!

o Accessing the class members:

python

print(my_dog.name) # Output: Rex

15. Write a function named DivExp which takes TWO parameters a, b and returns a value c
(=a/b). Write suitable assert for a>0 in function DivExp and raise an exception for when
b>0. Develop a suitable program which reads two values from the console and calls a
function DivExp.

o This is the same as question 7, so refer to that for the answer.

16. Describe Polymorphism functions to find histogram to count the number of times each
letter appears in a word or in sentence.

o Polymorphism allows di erent classes to be treated uniformly if they have a method


with the same name. Here's an example for counting letters:
python

class Word:

def __init__(self, text):

self.text = text

def histogram(self):

count = {}

for char in self.text:

if char.isalpha():

count[char] = count.get(char, 0) + 1

return count

class Sentence(Word):

def __init__(self, text):

super().__init__(text)

word = Word("hello")

sentence = Sentence("hello world")

print(word.histogram()) # Counts letters in "hello"

print(sentence.histogram()) # Counts letters in "hello world"

You might also like