PWP 1
PWP 1
-Example:
1. Read Mode ('r'):
-This is the default mode. It opens the file for reading.
-If the file doesn't exist, it raises a FileNotFoundError.
-When opened in this mode, attempting to write to the file will raise a UnsupportedOperation error.
-Example: open('file.txt', 'r')
-Key Points:
1. Code Reusability: Inheritance lets you write common functionalities once in the parent class and reuse them
in child classes, reducing code duplication.
2. Improved Structure: It promotes a cleaner and logical organization of code, making it easier to understand
and maintain.
3. Method Overriding: A child class can override a method from the parent class to provide a specific
implementation.
4. Extensibility: Existing classes can be extended to include new behaviors without modifying the original class.
- Syntax in Python:
class Parent:
# parent class code
class Child(Parent):
# child class code (inherits from Parent)
Here, there is a directory named pkg that contains two modules, mod1.py and mod2.py. The contents of the modules
are:
mod1.py
def m1():
print("first module")
mod2.py
def m2():
print("second module")
If the pkg directory resides in a location where it can be found, you can refer to the two modules with dot
notation(pkg.mod1, pkg.mod2) and import them with the syntax:
2. Method Overriding:
• Method overriding occurs when a child class redefines a method of its parent class.
• Used to implement runtime polymorphism and customize behavior in subclasses.
Example:
class Parent:
def show(self):
print("Parent class")
class Child(Parent):
def show(self):
print("Child class")
Q7. Explain Membership , Set , Bitwise , identity , assignment operators with example
Ans:
Membership operator:
-Membership operators are used to test if a value exists within a sequence like a list, tuple, string, or set.
-The two membership operators in Python are:
1. in: Returns True if the value is found in the sequence.
2. not in: Returns True if the value is not found in the sequence.
Example:
fruits = ['apple', 'banana', 'cherry']
print('apple' in fruits) # Output: True
This checks if 'apple' exists in the list fruits.
Bitwise Operators:
-Bitwise operators are used to perform operations on binary numbers (bits).
-They are applied to integers at the bit level.
-The main bitwise operators in Python are:
1. & (AND): Performs a bitwise AND operation.
2. | (OR): Performs a bitwise OR operation.
3. ^ (XOR): Performs a bitwise XOR (exclusive OR) operation.
4. ~ (NOT): Performs a bitwise NOT operation (inverts the bits).
5. << (Left Shift): Shifts bits to the left.
6. >> (Right Shift): Shifts bits to the right.
Set Operators :
-Set operators are used to perform operations like union, intersection, difference, and symmetric difference on sets.
-The main set operators in Python are:
1. | (Union): Combines all elements from two sets.
2. & (Intersection): Returns common elements between two sets.
3. - (Difference): Returns elements in the first set but not in the second.
4. ^ (Symmetric Difference): Returns elements that are in either of the sets, but not in both.
Identity Operators:
Identity operators are used to compare the memory locations of two objects. They are:
• is: Returns True if two variables refer to the same object (i.e., have the same memory address).
• is not: Returns True if two variables refer to different objects (i.e., have different memory addresses).
Example:
a = [1, 2, 3]
b = [1, 2, 3]
c=a
Assignment Operators:
Assignment operators are used to assign values to variables. The most commonly used assignment operator is:
• =: Assigns the value of the right-hand side to the left-hand variable.
• +=: Adds the right-hand value to the left-hand variable and assigns the result to the left-hand variable.
• -=, *=, /=, etc.: Perform the specified operation and assign the result to the left-hand variable.
Example:
x=5 # Assignment operator
y = 10
x += y #x=x+y
print(x) # Output: 15
Q8. Explain how try-catch block is used for exception handling in python.
Ans:
Exception Handling is a mechanism in Python used to handle runtime errors (exceptions) so that the normal flow of
the program is not interrupted. Instead of the program crashing when an error occurs, Python allows us to manage
these situations gracefully using exception handling blocks.
2. Method Overriding:
• Method overriding occurs when a child class redefines a method of its parent class.
• Used to implement runtime polymorphism and customize behavior in subclasses.
Example:
class Parent:
def show(self):
print("Parent class")
class Child(Parent):
def show(self):
print("Child class")
2) max(list) :
It returns the item that has the maximum value in a list
Example:
>>> list1
[1, 2, 3, 4, 5]
>>> max(list1)
5
3) sum(list) :
Calculates sum of all the elements of list.
Example:
>>>list1
[1, 2, 3, 4, 5]
>>>sum(list1)
15
4) min(list) :
It returns the item that has the minimum value in a list.
Example:
>>> list1
[1, 2, 3, 4, 5]
>>> min(list1)
1
import math_operations
print(math_operations.add(2, 3)) # Output: 5
Q14. Explain how to use user defined function in python with example
Ans:
-In Python, def keyword is used to declare user defined functions.
-The function name with parentheses (), which may or may not include parameters and arguments and a colon:
-An indented block of statements follows the function name and arguments which contains the body of the function.
-Syntax:
def function_name():
statements
.
.
-Example:
def fun():
print(“User defined function”)
fun()
-output:
User defined function
4. sort() – Sorts the list in ascending order (modifies the original list).
example:
my_list.sort()
1. if Statement
The if statement is the simplest form of decision making. It evaluates a condition (an expression that results in True or
False). If the condition is True, the block of code under if is executed. If it is False, nothing happens.
Syntax:
if condition:
# code block to execute if condition is True
2. if-else Statement
The if-else structure provides two possible paths: one for when the condition is True, and one for when it's False.
Syntax:
if condition:
# block executed if condition is True
else:
# block executed if condition is False
3. if-elif-else Statement
This structure is used when you have multiple conditions to test. Python will check each condition in sequence, and
the first one that is true will have its block executed. If none of the if or elif conditions are true, the else block is
executed.
Syntax:
if condition1:
# block if condition1 is True
elif condition2:
# block if condition2 is True
elif condition3:
# block if condition3 is True
else:
# block if none of the above conditions are True
Q17. Explain use of Pass and Else keyword with for loops in python.
Ans:
1. pass Keyword:
The pass keyword is a null statement used as a placeholder when a statement is required syntactically but you don't
want to execute any code. It allows the program to continue without doing anything.
• Usage: The pass keyword is typically used when you are working on a block of code that is not yet
implemented or when you need an empty block (like in a loop or a function).
Example:
for i in range(5):
if i == 3:
pass # Do nothing when i equals 3
else:
print(i)
Output:
0
1
2
4
tell():
-tell() returns the current position of the file pointer from the beginning of the file.
- Syntax:
file.tell()
Example:
f = open("demofile.txt", "r")
# points at the start
print(f.tell())
Q19. Explain Local and Global variable
Ans:
Local Variables:
-Local variables are those which are initialized inside a function and belongs only to that particular function.
-It cannot be accessed anywhere outside the function.
-Example:
def f():
# local variable
s = "I love Python Programming"
print(s)
# Driver code
f()
-Output: I love Python Programming
Global Variables:
-The global variables are those which are defined outside any function and which are accessible throughout the
program i.e. inside and outside of every function.
-Example:
# This function uses global variable s
def f():
print("Inside Function", s)
# Global scope
s = "I love Python Programming" f
() print("Outside Function", s)
Removing Elements
student.pop("course") # Removes 'course' key
del student["age"] # Deletes 'age' key
Q22. State the use of read() and readline () functions in python file handling.
Ans:
1. read([n]) Method:
-The read method reads the entire contents of a file and returns it as a string, if number of bytes are not given in the
argument.
-If we execute read(3), we will get back the first three characters of the file.
-Example: for read( ) method.
f=open("sample.txt","r")
print(f.read(5))
print(f.read())
2. readline([n]) Method:
-The readline() method just output the entire line whereas readline(n) outputs at most n bytes of a single line of a file.
-It does not read more than one line. Once, the end of file is reached, we get empty string on further reading.
-Example: For readline ( ) method.
f=open("sample.txt","r")
print(f.readline())
print(f.readline(3))
print(f.readline())
Q23. Describe 'Self Parameter with example.
Ans:
-In Python, the self parameter is a convention used in object-oriented programming (OOP) to refer to the instance of a
class within the class itself.
-It allows you to access the attributes and methods of the class from within its own methods.
-The name self is not a keyword in Python, but it is widely adopted and recommended as a convention.
- Example:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_info(self):
info = f"Make: {self.make}, Model: {self.model}, Year: {self.year}"
return info
def start_engine(self):
print("Engine started!")
# Create an instance of the Car class
my_car = Car("Toyota", "Corolla", 2022)
# Access the attributes using the self parameter
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
print(my_car.year) # Output: 2022
# Call the method using the self parameter
car_info = my_car.get_info()
print(car_info) # Output: Make: Toyota, Model: Corolla, Year: 2022
# Call the method that does not require any additional parameters
my_car.start_engine() # Output: Engine started!
2. max()
• Returns the maximum value in the tuple (only works if the elements are comparable).
t = (5, 10, 3)
print(max(t)) # Output: 10
3. min()
• Returns the minimum value in the tuple.
t = (5, 10, 3)
print(min(t)) # Output: 3
4. sum()
• Returns the sum of all numeric elements in the tuple.
t = (1, 2, 3)
print(sum(t)) # Output: 6
5. tuple()
• Converts another data type (like a list) into a tuple.
lst = [1, 2, 3]
t = tuple(lst)
print(t) # Output: (1, 2, 3)
Q25. Explain indexing and slicing in list
Ans:
What is a List?
A list in Python is an ordered, mutable collection of elements, which can be accessed using indexing and slicing.
Indexing in Lists
Indexing means accessing individual elements in a list using their position number.
• Index starts from 0 (for the first element).
• Negative indexing allows access from the end of the list (-1 is the last element).
Example:
fruits = ["apple", "banana", "cherry", "date"]
Slicing in Lists
Slicing is used to access a subsection of the list (a slice) using a range of indices.
Syntax:
list[start : end : step]
• start: index to begin the slice (inclusive).
• end: index to end the slice (exclusive).
• step: optional, how many elements to skip.
Example:
fruits = ["apple", "banana", "cherry", "date", "fig"]
#numbered indexes:
>>>txt2 =( "My name is {0}, I'm {1}".format("xyz",36))
>>>print(txt2)
My name is xyz, I'm 36
#empty placeholders:
>>>txt3 = ("My name is {}, I'm {}".format("pqr",36))
>>>print(txt3)
My name is pqr, I'm 36
Q27. Explain the Concept of indentation and variables
Ans:
i) Indentation:
• Python provides no braces to indicate blocks of code for class and function
definitions or flow control.
• Blocks of code are denoted by line indentation, which is compulsory.
• The number of spaces in the indentation is variable, but all statements within
the block must be indented the same amount.
• Example:
if True:
print "True"
else:
print "False"
• Thus, in Python all the continuous lines indented with same number of spaces
would form a block.
ii) Variables:
• Python Variable is containers that store values.
• We do not need to declare variables before using them or declare their type.
• A variable is created the moment we first assign a value to it.
• A Python variable is a name given to a memory location.
• It is the basic unit of storage in a program.
• Variable Naming Rules in Python
1) Variable name should start with letter(a-z ,A-Z) or underscore (_).
Example: age, _age, Age
2) In variable name, no special characters allowed other than underscore (_).
Example: age_, _age
3) Variables are case sensitive.
Example: age and Age are different, since variable names are case
sensitive.
4) Variable name can have numbers but not at the beginning.
Example: Age1
5) Variable name should not be a Python reserved keyword.
• Example:
x = 5 # x is of type integer
y = "John" # y is of type string
# Parent Class 2
class Parent2:
def greet(self):
print("Hello from Parent2!")
# Example of continue
for i in range(1, 10):
if i == 5:
continue # Skip when i equals 5
print(i) # Output: 1 2 3 4 6 7 8 9
# Example of pass
for i in range(1, 10):
if i == 5:
pass # Do nothing when i equals 5
print(i) # Output: 1 2 3 4 5 6 7 8 9
Q32. List VS Dictionary VS Tuple
Ans:
Feature List Dictionary Tuple
Ordered collection of Unordered collection of key- Ordered collection of
Definition
items value pairs items
Syntax my_list = [1, 2, 3] my_dict = {'key': 'value'} my_tuple = (1, 2, 3)
Order Yes (ordered) No (unordered) Yes (ordered)
Mutability Mutable Mutable Immutable
Keys are unique; values can be
Duplicates Allowed Allowed
duplicated
Accessing By index By key By index
Keys are immutable; values
Homogeneous/Heterogeneous Can store both types Can store both types
can be any type
Storing a collection of Storing key-value pairs for fast Storing a fixed
Use Case
items to modify lookup collection of items