PWP Try 3
PWP Try 3
Tuple is a collection of
List is a collection of ordered,
Definition ordered, immutable
mutable elements.
elements.
Methods Has more built-in methods (like Has fewer built-in methods
Available append(), extend(), remove()) (count(), index())
difference between Set, Tuple, and Dictionary in a clean row and column format
without emojis:
Yes (by
Indexed Access No Yes (by key)
position)
Duplicates
No Yes Keys - No, Values - Yes
Allowed
1
Concept of Inheritance in Python:- Inheritance is an OOP (Object-Oriented
Programming) concept that allows a class (child class) to acquire properties and
methods from another class (parent class). Python uses Method Resolution Order
(MRO) to decide which method to call when there are multiple parents.Multiple
inheritance allows the child to inherit all accessible properties and methods from
multiple parents.
Types of Inheritance in Python:-
Single Inheritance:- A child class inherits from one parent class. Child inherits from
Parent. It can access methods of Parent.
Multiple Inheritance:- A child class inherits from more than one parent class.
Child inherits from both Father and Mother.
Multilevel Inheritance A class is derived from a class which is already derived from
another class (grandparent → parent → child). Child inherits from Parent, and Parent
inherits from Grandparent.
Hierarchical Inheritance:- Multiple child classes inherit from the same parent class.
Both Child1 and Child2 inherit from the same Parent.
Hybrid Inheritance:- A combination of two or more types of inheritance. This
combines multilevel (A → B → D) and multiple (B, C → D) inheritance.
Example: Multiple Inheritance in Python
class Father:
def father_info(self):
print("Father's info")
class Mother:
def mother_info(self):
print("Mother's info")
class Child(Father, Mother):
def child_info(self):
print("Child's info")
obj = Child()
obj.father_info()
obj.mother_info()
obj.child_info()
2
Concept: User-Defined Package in Python:- A package is a collection of Python
modules organized in directories with an __init__.py file. This helps to logically
organize your code. my_package is the name of the package (a folder).greetings is a
module (a .py file) within that package.You use from my_package import greetings to
access functions. __init__.py is required to make Python treat the directory as a
package (can be empty).
Output:
Hello, Rahul!
Goodbye, Rahul!
Create class with name & roll number / ID and name and display
class Student:
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
def display_info(self):
print(f"Name: {self.name}")
print(f"Roll Number: {self.roll_no}")
student1 = Student("Aman", 101)
student1.display_info()
Output
Name: Aman
Roll Number: 101
3
Membership Operators in Python:- Membership operators are used to test
whether a value or variable is present in a sequence such as a string, list, tuple,
dictionary, or set. in checks if a value exists in a sequence. not in checks if a value
does not exist. Mainly used in conditions, loops, and search operations.
Types of Membership Operators:
In:- Returns True if the value is found in the sequence. Eg :- 'a' in 'apple' → True
not in :- Returns True if the value is not found. Eg 3 not in [1, 2, 3] → False
Examples:
# String print('h' in 'hello') # Output: True print('x' not in 'hello') # Output: True
Identity Operators:- Identity operators are used to compare memory locations of
two objects.
Is:- Returns True if both variables refer to the same object. Eg :- a is b
is not:- Returns True if they do not refer to the same object.eg :- a is not b
Bitwise Operators:- Bitwise operators operate on integers at the bit level.
& :- Bitwise AND eg :- 5 & 3 result :- 1
| :- Bitwise OR eg :- 5 | 3 result :- 7
^ :- Bitwise XOR eg :- 5 ^ 3 result :- 6
~ :- Bitwise NOT eg :- ~5 result :- -6
<< :- Left Shift eg :- 5 << 1 result :- 10
>> :- Right Shift eg :- 5 >> 1 result :- 2
Assignment Operators:- Assignment operators are used to assign values to
variables. Some also perform operations and then assign the result.
Assignment Operators
= :- Assign value eg :- x = 10 result :- x becomes 10
+= :- Add and assign eg :- x += 5 result :- x = x + 5
-= :- Subtract and assign eg :- x -= 2 result :- x = x - 2
*= :- Multiply and assign eg :- x *= 3 result :- x = x * 3
/= :- Divide and assign eg :- x /= 2 result :- x = x / 2
%= :- Modulus and assign eg :- x %= 3 result :- x = x % 3
**= :- Exponent and assign eg :- x **= 2 result :- x = x ** 2
//= :- Floor divide and assign eg :- x //= 2 result :- x = x // 2
4
The mkdir() function is used in programming to create a new directory (folder). It is
used to create a new empty folder. It may raise an error if the folder already exists
or if permissions are denied.
import os
os.mkdir("myFolder")
Type Examples
Digits 0–9
Tokens in Python:- Tokens are the smallest building blocks of a Python program,
like words in a sentence.
Types of Tokens:
1. Keywords – Reserved words with special meaning
Examples: if, else, True, False, return, import, lambda, etc.
2. Identifiers – Names for variables, functions, classes, etc.
Examples: square, num, a_lst
3. Literals – Fixed values used in code
o String Literals: 'Mayank', 'abc'
o Numeric Literals: 1, 1.2, -3.95
o Boolean Literals: True, False
o Special Literal: None (represents “nothing”)
5
Method Overloading:- Method Overloading means defining multiple methods
with the same name but different parameters in a class. Python does not
support traditional method overloading like Java or C++. Instead, it can be
achieved using default parameters or *args and **kwargs. Based on Number/type
of parameters. Purpose Perform similar tasks with different inputs
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
d = Dog()
d.speak() # Output: Dog barks
6
Modes of File Object in Python:- In Python, when opening a file using the open()
function, you must specify the mode — it defines how the file will be used (read,
write, append, etc.).
Common File Modes:
Mode Description
7
Summary – Python Data Types and Core Concepts
Basic Data Types:
String (str): Text data inside 'single' or "double" quotes. Characters can be
accessed using indexing.
Integer (int) and Float (float): Used for whole numbers and decimal
numbers. Can be used in arithmetic operations.
Boolean (bool): Holds True or False values. 1 is True, 0 is False.
Core Data Structures:
List: Ordered, mutable collection. Declared with brackets [].
Tuple: Ordered, immutable collection. Declared with parentheses ().
Dictionary: Collection of key-value pairs. Declared with {} using : for pairs.
Set: Unordered collection of unique items. Also declared with {} but without
key-value.
Examples:
x = 'abcd' (String)
x = [10, 20] (List)
x = (10, 20) (Tuple)
x = {'a': 1, 'b': 2} (Dictionary)
x = set(['a', 'b', 'a']) → {'a', 'b'} (Set)
Additional Concepts:
Control Structures: Direct the flow of code. Includes if-else, for, while, and
try-except.
Functions: Defined with def, used to group reusable code.
Modules: Python files with reusable code, imported using import.
Packages: Collections of modules grouped together for distribution and
reuse.
8
Exception:- An exception is an error that occurs during the execution of a program.
When Python encounters an error (like dividing by zero, accessing a missing file,
etc.), it raises an exception. If not handled, the program will crash. The try-except
block is used to catch and handle exceptions so the program doesn't crash.
Eg
class PasswordIncorrectError(Exception):
def __init__(self, message="Password is incorrect!"):
self.message = message
super().__init__(self.message)
def check_password(password):
correct_password = "Python@123" # Predefined correct password
if password != correct_password:
raise PasswordIncorrectError
else:
print("Access Granted. Password is correct.")
try:
user_password = input("Enter your password: ")
check_password(user_password)
except PasswordIncorrectError as e:
print("Access Denied:", e)
9
A dictionary in Python is created using curly braces {} and stores data in key:
value pairs. Eg student = { "roll_no": 1, "name": "Amit", "branch": "CO" }
You can access values by using the key inside square brackets or with the .get()
method. Eg print(student["name"]) # Output: Amit
print(student.get("roll_no")) # Output: 1
Removes the item with the specified key and returns its value. Raises error if key not
found. student.pop("branch")
print(student) # {'roll_no': 1, 'name': 'Amit'}
del statement :- Deletes a specific key-value pair.
del student["name"]
print(student) # {'roll_no': 1}
10
Four Built-in List Functions
append() – Adds an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
insert(index, element) – Inserts an element at a specific index.
my_list.insert(1, 10)
print(my_list) # Output: [1, 10, 2, 3, 4]
remove() – Removes the first occurrence of an element.
my_list.remove(10)
print(my_list) # Output: [1, 2, 3, 4]
sort() – Sorts the list in ascending order.
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
Four Built-in Functions on Set
add() – Adds an element to the set.
s = {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}
remove() – Removes an element from the set; gives error if not found.
s.remove(2)
print(s) # Output: {1, 3, 4}
discard() – Removes an element; does not give an error if not found.
s.discard(5) # No error
union() – Combines two sets, returns a new set with all unique elements.
a = {1, 2}
b = {2, 3}
print(a.union(b)) # Output: {1, 2, 3}
11
# Palindrome number checker
num = input("Enter a number: ")
# clean_text = text.replace(" ", "").lower()
if num == num[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
12
Local Variable:- A local variable is a variable that is declared inside a function
and can be used only within that function. It is created when the function starts
and destroyed when the function ends.
def my_function():
x = 10 # local variable
print("Local x:", x)
my_function()
# print(x) # This would cause an error because x is not defined outside the function
Global Variable:- A global variable is a variable that is declared outside all
functions and is accessible throughout the program, including inside functions (if
not shadowed).
x = 20 # global variable
def my_function():
print("Accessing global x inside function:", x)
my_function()
print("Accessing global x outside function:", x)
In Python, seek() and tell() are used to manipulate and track the position of the file
pointer while reading or writing files.
tell() Function:- Purpose: Returns the current position of the file pointer in number
of bytes from the beginning. Syntax: file.tell()
with open("example.txt", "r") as f:
print("Current position:", f.tell()) # Usually 0 at the beginning
content = f.read(5)
print("After reading 5 characters, position:", f.tell())
2. seek() Function:- Purpose: Changes the position of the file pointer to a
specific location.Syntax: file.seek(offset, whence)
with open("example.txt", "r") as f:
f.seek(7) # Move file pointer to 8th byte (index starts from 0)
print("After seeking to position 7:", f.read(5))
13
readline() Function:- Purpose: Reads only one line at a time from a file. Returns:
A single string containing the next line, including the newline character (\n)
with open("sample.txt", "r") as f:
line1 = f.readline()
line2 = f.readline()
print("Line 1:", line1)
print("Line 2:", line2)
readlines() Function:- Purpose: Reads all the lines of a file and returns them as a
list of strings. Returns: A list where each element is a line from the file.
with open("sample.txt", "r") as f:
lines = f.readlines()
print("Lines as list:", lines)
In Python, indentation is used to define the structure of the code. It determines the
grouping of statements and the hierarchy of blocks of code, such as loops, functions,
and conditionals. Unlike other programming languages, where braces {} are used to
define blocks, Python relies on indentation to create readable, clean code.
Key Roles:- Defines Code Blocks: Ensures Code Readability:
14
Decision making statements allow you to execute specific blocks of code based on
certain conditions. Python provides two common decision-making structures: if-else
and if-elif-else.
if-else Statement:- The if-else statement evaluates a condition and executes the
corresponding block of code based on whether the condition is True or False.
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
2. if-elif-else Statement:- The if-elif-else statement allows checking multiple
conditions. If the first condition is False, it checks the next condition (elif) and so on.
If none of the conditions are True, the else block is executed.
x = 15
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10 but less than or equal to 20")
else:
print("x is 10 or less")
15
# Loop to print the pattern
num = 2 # Starting number
for i in range(1, 4): # for i in range(1, 5):
for j in range(i): # for j in range(1, i + 1):
print(num, end=" ") # print(j, end=" ")
num += 2 # Increment by 2 to get the next even number
print() # To move to the next line
2
468
10 12 14 16 18
16