Python Programming Questions and Answers
1. Backing up a folder into a ZIP file
import os
import zipfile
def backup_to_zip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
zip_filename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zip_filename):
break
number += 1
print(f'Creating {zip_filename}...')
with zipfile.ZipFile(zip_filename, 'w') as backup_zip:
for foldername, subfolders, filenames in os.walk(folder):
print(f'Adding files in {foldername}...')
backup_zip.write(foldername)
for filename in filenames:
backup_zip.write(os.path.join(foldername, filename))
print('Backup complete.')
# Example usage:
# backup_to_zip('my_folder')
2. Interface in Python
In Python, an interface is a way to define a contract for what a class should do, without specifying
how it should do it. This is often achieved using abstract base classes (ABCs) from the `abc`
module.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
def perimeter(self):
return 2 * 3.14 * self.radius
# Example usage:
# circle = Circle(5)
# print(circle.area())
# print(circle.perimeter())
3. Explanation of Commands
- **move()**: Moves a file or directory to another location.
import shutil
shutil.move('source.txt', 'destination_folder/')
- **unlink()**: Removes a file.
import os
os.unlink('file_to_remove.txt')
- **rmdir()**: Removes an empty directory.
import os
os.rmdir('empty_folder')
- **rmtree()**: Removes a directory and all its contents.
import shutil
shutil.rmtree('folder_to_remove')
- **extractall()**: Extracts all contents of a ZIP file.
import zipfile
with zipfile.ZipFile('archive.zip', 'r') as zip_ref:
zip_ref.extractall('extracted_folder')
4. Detailed Explanation
- **Debugger**: A tool that allows developers to inspect and control the execution of a program. It
helps in finding and fixing bugs by providing functionalities like breakpoints, step execution, and
variable inspection.
- **Functionality of Debug Control Window**: This window in a debugger allows users to control the
flow of program execution. It typically provides options to start/stop execution, step through code
line-by-line, and inspect variables.
- **Exceptions**: Errors that occur during the execution of a program. They can be handled using
try-except blocks to prevent the program from crashing.
- **Assertions**: Statements used during debugging to check if a condition is true. If the condition is
false, an `AssertionError` is raised.
5. Code Snippets
- **Copying files and folders using shutil module**
import shutil
# Copy a file
shutil.copy('source.txt', 'destination.txt')
# Copy a directory
shutil.copytree('source_folder', 'destination_folder')
- **os.walk()**: Generates the file names in a directory tree.
import os
for dirpath, dirnames, filenames in os.walk('my_directory'):
print(f'Found directory: {dirpath}')
for file_name in filenames:
print(f'\tFile: {file_name}')
- **Creating and adding to a ZIP file**
import zipfile
with zipfile.ZipFile('new_archive.zip', 'w') as zipf:
zipf.write('file_to_add.txt')
6. Class 'Complex' for Complex Numbers
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
def __str__(self):
return f'{self.real} + {self.imag}i'
# Example usage:
n = int(input("Enter the number of complex numbers: "))
complex_numbers = [Complex(float(input("Enter real part: ")), float(input("Enter imaginary part: ")))
for _ in range(n)]
result = sum(complex_numbers, Complex(0, 0))
print(f'Sum of complex numbers: {result}')
7. Objects and Classes
- **Classes**: Blueprints for creating objects. They encapsulate data and functions.
- **Objects**: Instances of classes.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f'{self.name} says woof!')
# Example usage:
dog1 = Dog('Buddy', 5)
dog1.bark()
8. Operator Overloading
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)
def __str__(self):
return f'({self.x}, {self.y})'
# Example usage:
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3) # Output: (4, 6)
9. Class 'Student' for Marks Calculation
class Student:
def __init__(self, name):
self.name = name
self.marks = []
def add_marks(self, mark):
self.marks.append(mark)
def total_marks(self):
return sum(self.marks)
def percentage(self):
return self.total_marks() / len(self.marks) * 100
def display(self):
print(f'Student Name: {self.name}')
print(f'Total Marks: {self.total_marks()}')
print(f'Percentage: {self.percentage()}%')
# Example usage:
student = Student('Alice')
student.add_marks(90)
student.add_marks(85)
student.add_marks(88)
student.display()
10. __init__ Method
The __init__ method is a constructor in Python classes. It initializes the object's attributes.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f'Car Brand: {self.brand}, Model: {self.model}')
# Example usage:
car = Car('Toyota', 'Corolla')
car.display_info()
11. Interface in Python (Repeat)
Python does not have formal interfaces like some other languages, but abstract base classes
(ABCs) can be used to define a set of methods that must be created within any child classes built
from the abstract base class.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
# Example usage:
dog = Dog()
print(dog.sound())