Python Notes

IT Concepts, Algorithms & University Q&A

2-Mark Questions

1. What is Inheritance?

Inheritance allows one class (Child class) to acquire and reuse the properties (attributes and methods) of another class (Parent class). This promotes code reusability and establishes a logical hierarchical structure.

2. What is a Class?

A Class is a logical blueprint or template for creating objects. It defines the variables (attributes) and behaviors (methods) that are common to all objects of that specific type.

3. What is an Object?

An Object (also called an Instance) is a physical manifestation or specific entity created from a class blueprint.

5-Mark Questions

1. Write a program to find if a number is odd.

(Applying the modulo % operator and if-else branching):

# Program to check if a number is odd
num = int(input("Enter a number: "))

if num % 2 != 0:
    print(num, "is an Odd number")
else:
    print(num, "is an Even number")

2. Write a program to find the largest among 3 numbers.

(Applying the if-elif-else ladder concept):

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:
    print("A is the largest")
elif b >= a and b >= c:
    print("B is the largest")
else:
    print("C is the largest")

3. Explain classes and instances with a program (including concepts of objects and constructors).

  • Class: A blueprint for creating objects.
  • Instance (Object): An object created from a class.
  • Constructor (__init__): A special method called automatically when an object is created. It is used to initialize the object's initial state (attributes).
  • self parameter: Represents the specific instance of the class and allows access to its attributes.
class Student:
    # Constructor
    def __init__(self, name, age):
        self.name = name  # Initializing attributes
        self.age = age

# Creating an instance (object)
s1 = Student("Ravi", 20) 

# Accessing instance variables
print(s1.name, s1.age) 
# Output: Ravi 20

4. Explain class and object with a program.

  • Class: The blueprint.
  • Object: The instance of the class.
class Student:
    def display(self):
        print("Student Class")

# Creating an Object
s1 = Student() 

# Calling a method using the object
s1.display()

5. Explain the structure of a Python program with an example.

A Python program is a collection of statements executed by the Python interpreter in a top-down sequential manner. Unlike C or Java, Python does not require a compulsory main() function and relies heavily on indentation to define blocks of code.

A typical Python program consists of:

  1. Import statements: Used to include modules.
  2. Variable declarations and initializations.
  3. Function definitions.
  4. Executable (main) statements.
import math        # 1. Import section

x = 10             # 2. Variable declaration
y = 20

def add(a, b):     # 3. Function definition
    return a + b

result = add(x, y) # 4. Execution
print(result)

10-Mark Questions

1. Exception Handling and re module

Part A: Exception Handling

An exception is a runtime error that disrupts program execution. Exception handling prevents the program from crashing, allows graceful error handling, and provides a better user experience.

It uses four main blocks:

  • try: Contains the code that might throw an error.
  • except: Contains the code that handles the error if it occurs.
  • else: Executed only if no error occurs in the try block.
  • finally: Always executed, regardless of whether an exception occurs or not (used for cleanup).
try:
    x = int(input("Enter number: "))
    print(10 / x)
except ZeroDivisionError:
    print("Division by zero")
except ValueError:
    print("Invalid input")
finally:
    print("Program ended")

Part B: Regular Expressions (re module)

A regular expression (regex) is a pattern used to match, search, or manipulate strings. Python provides the re module for handling these operations.

Common Functions:
  • re.match(): Checks for a match only at the beginning of the string.
  • re.search(): Scans the entire string for the first match.
  • re.findall(): Returns a list containing all matches.
  • re.sub(): Replaces occurrences of a pattern with a new string.
import re

# Finding all numbers in a string
pattern = r"\d+"
text = "Age is 20 and ID is 105"

print(re.findall(pattern, text)) 
# Output: ['20', '105']

2. Branching and Looping

Part A: Branching Statements

Branching allows a program to decide between alternative paths based on specific conditions. This forms the core of logical decision-making in Python.

  • if: Executes a block if the condition is True.
  • if–else: Two-way decision.
  • if–elif–else: Multi-way decision (ladder).
  • Nested if: An if statement inside another if statement.
a = 10
b = 20

if a > b:
    print("A is greater")
else:
    print("B is greater")
# Output: B is greater

Part B: Looping Statements

Loops avoid code repetition and allow a block of code to be executed repeatedly. They make programs efficient and scalable.

  • for loop (Sequence-based): Used when the number of iterations is known. It iterates over a sequence (like a list or range).
  • while loop (Condition-based): Used when the number of iterations is unknown. It executes as long as a condition remains True.
# For loop using range
for i in range(1, 6):
    print(i)
# Output: 1 2 3 4 5

Role in Problem Solving:

Together, branches (decision making) and loops (repetition) provide powerful control structures to solve real-world problems like factorial calculation, number classification, and searching.

# Example solving a problem (Factorial):
n = 5
fact = 1
for i in range(1, n+1):
    fact *= i  # Loop performs repetition
print("Factorial is:", fact) 
# Output: 120