0% found this document useful (0 votes)
17 views47 pages

Python Notes 1

The document provides a comprehensive overview of Python programming concepts, including algorithms, data types like tuples, string formatting, and various built-in functions. It also covers practical programming examples such as Fibonacci sequence generation, prime number checks, and file operations. Additionally, it discusses loop theory, exception handling, and inheritance in Python.

Uploaded by

rahul banerjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views47 pages

Python Notes 1

The document provides a comprehensive overview of Python programming concepts, including algorithms, data types like tuples, string formatting, and various built-in functions. It also covers practical programming examples such as Fibonacci sequence generation, prime number checks, and file operations. Additionally, it discusses loop theory, exception handling, and inheritance in Python.

Uploaded by

rahul banerjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 47

PYTHON NOTES

1. What is an Algorithm?
An algorithm is a step-by-step procedure or a finite set of instructions to solve a problem or perform
a computation. It is a logical approach for achieving a specific goal in a defined manner.

2. What is a tuple?
A tuple is an immutable, ordered collection of elements in Python. It is defined by placing elements
inside parentheses ( ), separated by commas. Example:
_
my_tuple = (1, 2, 3)

3. How to slice a list in Python?


List slicing extracts a portion of a list using the syntax: list[start:stop:step].
start: Starting index (inclusive).
stop: Ending index (exclusive).
step: Step size (default is 1).
Example:
my_list = [10, 20, 30, 40, 50]
sliced_list = my_list[1:4] # Output: [20, 30, 40]

4. Explain different string formats in Python with examples (5 Marks).

f-strings (formatted strings):


name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

str.format():
print("My name is {} and I am {} years old.".format(name, age))

Percent formatting:
print("My name is %s and I am %d years old." % (name, age))

Template Strings (using string.Template):


from string import Template
t = Template("My name is $name and I am $age years old.")
print(t.substitute(name="Alice", age=25))

5. Discuss int(), float(), str(), chr(), and complex() with examples.

int(): Converts a value to an integer.


print(int(3.5)) # Output: 3
print(int("10")) # Output: 10

float(): Converts a value to a floating-point number.


print(float(3)) # Output: 3.0

str(): Converts a value to a string.


print(str(10)) # Output: '10'
chr(): Converts an integer to its corresponding Unicode character.
print(chr(65)) # Output: 'A'

complex(): Converts to a complex number.


print(complex(3, 4)) # Output: (3+4j)

6. Discuss ord(), hex(), oct(), complex(), and float() with examples.


ord(): Converts a character to its Unicode code.
print(ord('A')) # Output: 65

hex(): Converts a number to a hexadecimal string.


print(hex(255)) # Output: '0xff'

oct(): Converts a number to an octal string.


print(oct(8)) # Output: '0o10'

complex(): Converts numbers to a complex number.


print(complex(2, -3)) # Output: (2-3j)

float(): Converts a value to a floating-point number.


print(float("3.14")) # Output: 3.14

7. Fibonacci sequence up to nth term (Program).


n = int(input("Enter the number of terms: "))
a, b = 0, 1
print("Fibonacci sequence:")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

8. Check for the largest number until user enters "done".


largest = None
while True:
num = input("Enter a number (or 'done' to stop): ")
if num == 'done':
break
try:
num = int(num)
if largest is None or num > largest:
largest = num
except ValueError:
print("Invalid input. Please enter a number.")
print("Largest number:", largest)

9. Sum of all odd and even numbers up to a specified number.


_
_
n = int(input("Enter a number: "))
odd_sum = sum(i for i in range(1, n + 1) if i % 2 != 0)
even_sum = sum(i for i in range(1, n + 1) if i % 2 == 0)
print("Sum of odd numbers:", odd_sum)
print("Sum of even numbers:", even_sum)

10. Need for continue and break statements (Prime number check).
break: Terminates the loop.
continue: Skips the current iteration.

Program to check if a number is prime:


num = int(input("Enter a number: "))
if num < 2:
print("Not a prime number")
else:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print("Not a prime number")
break
else:
print("Prime number")

11. Need for catching exceptions using try and except


Catching exceptions prevents the program from crashing and allows graceful handling of errors.
Example:
_
_
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")

12. Describe the syntax for given functions with examples.


abs(x): Returns the absolute value.
print(abs(-5)) # Output: 5

max(*args): Returns the largest value.


print(max(1, 5, 3)) # Output: 5

divmod(a, b): Returns a tuple (quotient, remainder).


print(divmod(10, 3)) # Output: (3, 1)

pow(a, b): Computes a**b.


print(pow(2, 3)) # Output: 8

len(obj): Returns the length of an object.


print(len("hello")) # Output: 5

13. Solve quadratic equation.


import math
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
discriminant = b**2 - 4*a*c

if discriminant >= 0:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
print("Roots:", root1, root2)
else:
print("No real roots")

14. Find area and perimeter of a circle using functions.


def circle_area(radius):
return 3.14159 * radius**2

def circle_perimeter(radius):
return 2 * 3.14159 * radius

r = float(input("Enter the radius: "))


print("Area:", circle_area(r))
print("Perimeter:", circle_perimeter(r))

15. Find nPr and nCr without using factorial().


def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

def nPr(n, r):


return factorial(n) // factorial(n - r)

def nCr(n, r):


return nPr(n, r) // factorial(r)

n = int(input("Enter n: "))
r = int(input("Enter r: "))
print("nPr:", nPr(n, r))
print("nCr:", nCr(n, r))

1. Replace Commas with Hyphens and Sort Words:

sentence = input("Enter comma-separated words: ")


words = sentence.split(',')
words.sort()
print('-'.join(words))

List Functions
3. List Functions:
o len(): Returns the number of elements in a list.
Example: len([1, 2, 3]) → Output: 3
o sum(): Returns the sum of elements in a list (numeric only).
Example: sum([1, 2, 3]) → Output: 6
o any(): Returns True if any element in the list is True.
Example: any([0, 1, 0]) → Output: True
o all(): Returns True if all elements in the list are True.
Example: all([1, 2, 3]) → Output: True
o sorted(): Returns a sorted version of the list.
Example: sorted([3, 1, 2]) → Output: [1, 2, 3]
4. List Methods:
o append(x): Adds x at the end of the list.
Example: [1, 2].append(3) → Output: [1, 2, 3]
o extend(iterable): Appends elements of an iterable to the list.
Example: [1, 2].extend([3, 4]) → Output: [1, 2, 3, 4]
o insert(i, x): Inserts x at index i.
Example: [1, 3].insert(1, 2) → Output: [1, 2, 3]
o index(x): Returns the first index of x.
Example: [1, 2, 3].index(2) → Output: 1
o sort(): Sorts the list in ascending order.
Example: [3, 1, 2].sort() → Output: [1, 2, 3]

Sorting and Unique Character Analysis


5. Check List Order:

def check_order(lst):
if lst == sorted(lst):
print("List is sorted in ascending order.")
elif lst == sorted(lst, reverse=True):
print("List is sorted in descending order.")
else:
print("Items in list are not sorted.")

lst = [int(x) for x in input("Enter numbers: ").split()]


check_order(lst)

6. Sort Words by Length:

sentence = input("Enter a sentence: ")


words = sentence.split()
sorted_words = sorted(words, key=len, reverse=True)
for word in sorted_words:
print(word, len(word))

7. Unique Characters in Strings:

def unique_chars(*strings):
for s in strings:
print(f"Unique characters in '{s}': {set(s)}")
unique_chars("hello", "world", "")

8. Most Frequent Characters:

def most_frequent(s):
frequency = {}
for char in s:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
sorted_frequency = sorted(frequency.items(), key = lambda x: x[1], reverse=True)
for char, freq in sorted_frequency:
print(char, freq)
most_frequent("abracadabra")

File Operations
10. Access Modes:
o 'r': Read mode (default).
o 'w': Write mode (overwrites the file).
o 'a': Append mode.
o 'rb', 'wb': Read/Write in binary mode.
11. File Methods:
o read(): Reads the entire content.
o readline(): Reads a single line.
o readlines(): Reads all lines into a list.
o tell(): Returns the current position.
o seek(): Moves the cursor to the specified position.
o write(): Writes to the file.
12. Reverse Words in File:

with open("secret_societies.txt", "r") as file:


content = file.read()
reversed_content = ' '.join(word[::-1] for word in content.split())
print(reversed_content)
13. Word Count in File:

with open("quotes.txt", "r") as file:


content = file.read()
words = content.split()
word_count = len(words)
occurrences = {word: words.count(word) for word in set(words)}

print("Word Count:", word_count)


print("Occurrences:", occurrences)
14. Longest Word in File:

file_name = input("Enter file name: ")


with open(file_name, "r") as file:
longest_word = max(file.read().split(), key=len) # key=len for finding the "maximum" is the length of each word.
print("Longest word:", longest_word)

Inheritance
15. Inheritance and super():

class Parent:
def show(self):
print("Parent method")

class Child(Parent):
def show(self):
super().show()
print("Child method")

obj = Child()
obj.show()
16. Overriding Base Class Method:

class Base:
def display(self):
print("Base class")

class Derived(Base):
def display(self):
print("Derived class")

obj = Derived()
obj.display()

Loop Theory

1. Purpose of Loops:

o Used for repeated execution of code blocks.

2. For vs While Loops:

o for loop: Iterates over a sequence.


for i in range(5):

print(i)

o while loop: Repeats as long as a condition is True.

i=0

while i < 5:

print(i)

i += 1

3. range() Function:

o Generates sequences.

for i in range(1, 10, 2):

print(i) # Outputs: 1, 3, 5, 7, 9

4. break Statement:

o Exits the loop prematurely.

for i in range(10):

if i == 5:

break

5. continue Statement:

o Skips the current iteration.

for i in range(5):

if i == 3:

continue

print(i)

6. Nested Loops:
for i in range(3):

for j in range(2):

print(f"i={i}, j={j}")

7. Iterating Over Strings/Lists:

for char in "hello":

print(char)

8. Infinite Loops:

o Occur when conditions never evaluate to False.


Avoid using: while True without a break.

9. Sum of List Elements:

lst = [1, 2, 3, 4]

total = sum(lst)

print(total)

10. else Clause in Loops:

o Executes if the loop is not exited with break.

for i in range(5):

print(i)

else:

print("Completed without break")

If-Else Statements

1. Purpose of If-Else Statements:

o Used for decision-making based on conditions.


Example:
x = 10

if x > 5:

print("Greater")

else:

print("Smaller")

String Theory Questions

1. Define a string in and explain its characteristics.

o Strings are sequences of characters enclosed within single (' '), double (" "), or triple
quotes (''' ''').

o Strings are immutable, indexed, and iterable.

Answer Example:

s = "Hello, World!"

print(s[0]) # H

print(s[-1]) # !

2. What are the different ways to create strings in ?

o Using single/double quotes: s = 'hello'

o Using triple quotes: s = '''hello'''

o Using the str() function: s = str(123)

3. Explain string indexing and slicing with examples.

Answer Example:

s = ""

print(s[0]) # Output: P

print(s[-1]) # Output: n
print(s[1:4]) # Output: yth

4. What does it mean that strings in are immutable? Why is this important?

o Strings cannot be changed once created. Any modification creates a new string.

o Immutability ensures string safety and efficient memory use.

Example:

s = "hello"

s[0] = 'H' # Raises error

5. List and describe five common string methods in .

o lower(): Converts to lowercase.

o upper(): Converts to uppercase.

o strip(): Removes whitespace.

o replace(): Replaces a substring.

o split(): Splits string by delimiter.

Answer Example:

s = " Hello World "

print(s.strip()) # "Hello World"

6. How do escape sequences work in strings? Give examples.

o Escape sequences allow inserting special characters.

▪ \n: Newline

▪ \t: Tab

▪ \\: Backslash

▪ \': Single Quote

Example:
print("Hello\nWorld") # Newline

print("He said, \"\" is fun.") # Double quotes

Loop Theory Questions

1. What is a loop in , and why is it used?

o A loop is a construct to execute a block of code repeatedly until a condition is met.

2. Differentiate between for and while loops with examples.

o for loop: Iterates over sequences.

for i in range(3):

print(i) # 0, 1, 2

o while loop: Executes based on a condition.

x=0

while x < 3:

print(x)

x += 1

3. Explain the concept of the range() function in a for loop.

o range(start, stop, step) generates numbers in a sequence.

Example:

for i in range(1, 10, 2):

print(i) # 1, 3, 5, 7, 9

4. What is the purpose of the break statement in a loop?


o Exits the loop prematurely.

Example:

for i in range(5):

if i == 3:

break

print(i)

5. What is the else clause in a loop?

o Executes after the loop finishes unless terminated by break.

Example:

for i in range(3):

print(i)

else:

print("No break occurred.")

Write Program to Demonstrate Multiple Inheritance.

Answer:

class Parent1:

def feature1(self):

print("Feature 1 from Parent1")

class Parent2:

def feature2(self):

print("Feature 2 from Parent2")


class Child(Parent1, Parent2):

def feature3(self):

print("Feature 3 from Child")

obj = Child()

obj.feature1()

obj.feature2()

obj.feature3()

7. Given the Coordinates (x, y) of a Center of a Circle and Its Radius, Write Program to Determine
Whether the Point Lies Inside the Circle, on the Circle, or Outside the Circle.

Answer:

import math

def point_circle_relation(xc, yc, r, xp, yp):

distance = math.sqrt((xp - xc) ** 2 + (yp - yc) ** 2)

if distance < r:

print("Point lies inside the circle")

elif distance == r:

print("Point lies on the circle")

else:

print("Point lies outside the circle")

xc, yc, r = map(float, input("Enter circle center (x, y) and radius: ").split())

xp, yp = map(float, input("Enter point (x, y): ").split())

point_circle_relation(xc, yc, r, xp, yp)

8. Write Program to Demonstrate Multiple Inheritance with Method Overriding.

Answer:
class Parent1:

def display(self):

print("Display from Parent1")

class Parent2:

def display(self):

print("Display from Parent2")

class Child(Parent1, Parent2):

def display(self):

super().display() # Calls Parent1's method by default in case of multiple inheritance

print("Display from Child")

obj = Child()

obj.display()

String Theory Questions

1. Define a string in and explain its characteristics.

• A string is a sequence of characters enclosed in single, double, or triple quotes.

• Strings are immutable, indexed, iterable, and support many built-in methods.

Example:

s = "Hello, World!"

print(s[0]) # H

print(s[-1]) # !

2. What are different ways to create strings in ?

• Using single quotes: s = 'hello'


• Using double quotes: s = "hello"

• Using triple quotes for multi-line strings: s = '''hello'''

3. Explain string indexing and slicing with examples.

Example:

s = ""

print(s[0]) # Output: P

print(s[-1]) # Output: n

print(s[1:4]) # Output: yth

4. What does it mean that strings in are immutable? Why is this important?

• Once created, strings cannot be modified.

• Immutability ensures safe sharing and efficient memory management.

Example:

s = "hello"

# s[0] = 'H' # Raises error

5. List and describe five common string methods in .

• lower(): Converts to lowercase.

• upper(): Converts to uppercase.

• strip(): Removes leading and trailing spaces.

• replace(): Replaces a substring with another.

• split(): Splits a string by a delimiter into a list.

Example:

s = " Hello World "


print(s.strip()) # "Hello World"

6. How do escape sequences work in strings? Give examples.

• Escape sequences allow using special characters like newline (\n), tab (\t), etc.

Example:

print("Hello\nWorld") # Newline

print("He said, \" is fun.\"") # Double quotes

Loop Theory Questions

1. What is a loop in , and why is it used?

• A loop is used to execute a block of code repeatedly until a condition is met.

2. Differentiate between for and while loops with examples.

• for loop: Iterates over sequences like lists or ranges.

for i in range(3):

print(i) # 0, 1, 2

• while loop: Runs as long as the condition is True.

x=0

while x < 3:

print(x)

x += 1

3. Explain the concept of the range() function in a for loop.

• range(start, stop, step) generates a sequence of numbers.

Example:
for i in range(1, 10, 2):

print(i) # 1, 3, 5, 7, 9

4. What is the purpose of the break statement in a loop?

• Exits the loop prematurely when a condition is met.

Example:

for i in range(5):

if i == 3:

break

print(i)

5. How does the continue statement function within a loop?

• Skips the current iteration and moves to the next one.

Example:

for i in range(5):

if i == 3:

continue

print(i)

6. What is a nested loop, and when would you use it?

• A loop inside another loop, used for multi-level iterations.

Example:

for i in range(3):
for j in range(2):

print(f"i={i}, j={j}")

7. Explain how to use a loop to iterate over a string or list.

Example:

s = ""

for char in s:

print(char)

8. What are infinite loops, and how can they be avoided?

• Loops that never terminate due to a faulty condition.

Example:

while True: # Avoid by adding a proper exit condition.

break

9. Describe the use of the else clause in a loop.

• Executes after a loop finishes unless terminated by break.

Example:

for i in range(3):

print(i)

else:

print("Loop finished without break.")

If-Else Statements Theory Questions

1. What is the difference between if, elif, and else statements?


• if: The first conditional check. If true, the block runs.

• elif: Additional condition(s) to check if the previous if or elif is false.

• else: Runs if all prior conditions are false.

Example:

x = 10

if x > 15:

print("Greater than 15")

elif x > 5:

print("Greater than 5 but not 15")

else:

print("5 or less")

2. What are nested if-else statements, and when are they useful?

• Nested if-else: An if or else inside another if or else. Useful for checking multiple conditions
hierarchically.

Example:

x = 20

if x > 10:

if x < 25:

print("Between 10 and 25")

else:

print("Greater than or equal to 25")

else:

print("10 or less")

3. How does evaluate multiple conditions in an if statement?

• Logical Operators: Conditions are combined using and, or, or not.


• Evaluated left-to-right, stopping as soon as the result is known (short-circuiting).

Example:

x, y = 5, 10

if x < 10 and y > 5:

print("Both conditions are true")

4. What is the significance of indentation in if-else statements in ?

• uses indentation to define blocks of code. Without proper indentation, it raises an


IndentationError.

Example (Correct):

x=5

if x > 0:

print("Positive number")

Example (Incorrect):

x=5

if x > 0:

print("Positive number") # IndentationError

5. Can an else statement exist without an if statement? Explain.

• No, an else statement must follow an if or elif.

Incorrect Example:

else:

print("This is invalid") # SyntaxError


6. Explain short-circuit evaluation in the context of if-else statements.

• Short-circuiting stops evaluating conditions as soon as the result is known.

o and stops if the first condition is false.

o or stops if the first condition is true.

Example:

x=5

if x > 10 and x / 0 == 0: # Short-circuits, so no ZeroDivisionError

print("Will not execute")

7. How can you use if-else statements to check for even or odd numbers?
Example:

x = int(input("Enter a number: "))

if x % 2 == 0:

print("Even")

else:

print("Odd")

8. What is the difference between == and = in an if-else condition?

• =: Assignment operator, used to assign values.

• ==: Comparison operator, checks equality.

Example:

x = 5 # Assignment

if x == 5: # Comparison

print("x equals 5")


9. Describe how to use if-else statements to find the largest number among three values.
Example:

a, b, c = map(int, input("Enter three numbers: ").split())

if a > b and a > c:

print("Largest:", a)

elif b > c:

print("Largest:", b)

else:

print("Largest:", c)

Math Functions Basics Theory Questions

1. What are math functions in Python, and where are they found?

• Math functions are predefined functions used for mathematical operations.

• Found in the math module.

2. Explain the purpose of the math module in .

• Provides advanced mathematical functions like trigonometry, logarithms, and constants like
π.

Example:

import math

print(math.pi) # 3.141592653589793

3. What is the difference between abs() and math.fabs()?

• abs(): Built-in function for absolute values. Works for integers and floats.

• math.fabs(): Found in math module. Always returns a float.

Example:
print(abs(-5)) # 5

import math

print(math.fabs(-5)) # 5.0

4. Explain how to calculate the square root of a number in .

• Use math.sqrt() for the square root.

Example:

import math

print(math.sqrt(16)) # 4.0

5. How does handle trigonometric functions? Provide examples.

• Found in the math module: sin(), cos(), tan(), etc.

Example:

import math

angle = math.radians(30) # Convert degrees to radians

print(math.sin(angle)) # 0.5

6. Describe the pow() function and how it differs from the ** operator.

• pow(x, y): Returns x^y.

• ** operator: Equivalent but supports more concise syntax.

Example:

print(pow(2, 3)) # 8

print(2 ** 3) # 8
Math Functions Basics Theory Questions

1. What is the purpose of math.factorial()?

• Computes the factorial of a non-negative integer nnn, defined as n!=n×(n−1)×…×1n! = n


\times (n-1) \times \ldots \times 1n!=n×(n−1)×…×1.

• Useful in combinatorics, probability, and other mathematical computations.

Example:

import math

print(math.factorial(5)) # Output: 120

2. Explain how to find the greatest common divisor (GCD) of two numbers in .

• Use math.gcd(a, b) to find the GCD.

Example:

import math

print(math.gcd(48, 18)) # Output: 6

3. What is math.pi, and how is it used in calculations?

• Represents the mathematical constant π\piπ, approximately 3.14159.

• Used in calculations involving circles, trigonometry, and more.

Example:

import math

radius = 5

area = math.pi * radius ** 2

print(area) # Area of the circle

4. How does handle rounding of numbers, and what functions are available for this purpose?
• provides functions for rounding:

o round(x, n): Rounds to n decimal places.

o math.floor(x): Rounds down to the nearest integer.

o math.ceil(x): Rounds up to the nearest integer.

Example:

import math

print(round(3.456, 2)) # Output: 3.46

print(math.floor(3.7)) # Output: 3

print(math.ceil(3.3)) # Output: 4

List Theory Questions

1. What is a list in Python, and how is it different from other data types?

• A list is an ordered, mutable collection of elements.

• Can hold heterogeneous data types, unlike arrays.

2. Describe how to create a list in . Provide examples.


Example:

my_list = [1, 2, 3, "apple", True]

3. Explain the mutability of lists and why it is important.

• Lists are mutable, meaning elements can be modified after creation.


Example:

my_list = [1, 2, 3]

my_list[0] = 10

print(my_list) # Output: [10, 2, 3]


4. How do you access elements in a list by index?

• Use square brackets with the index.


Example:

my_list = [10, 20, 30]

print(my_list[1]) # Output: 20

5. What is list slicing, and how does it work?

• Access a subset of elements using [start:stop:step].


Example:

my_list = [1, 2, 3, 4, 5]

print(my_list[1:4]) # Output: [2, 3, 4]

6. Explain how to add elements to a list using append(), extend(), and insert().
Example:

my_list = [1, 2]

my_list.append(3) # Adds a single element

my_list.extend([4, 5]) # Adds multiple elements

my_list.insert(1, 10) # Adds at a specific position

print(my_list) # Output: [1, 10, 2, 3, 4, 5]

7. What are the different methods to remove elements from a list?

• pop(): Removes by index.

• remove(): Removes by value.

• clear(): Removes all elements.

8. How can you find the length of a list in ?


• Use len().
Example:

my_list = [1, 2, 3]

print(len(my_list)) # Output: 3

9. Explain the purpose and usage of list comprehensions.

• A concise way to create lists.


Example:

squares = [x**2 for x in range(5)]

print(squares) # Output: [0, 1, 4, 9, 16]

10. What is the difference between pop() and remove() in lists?

• pop(index): Removes by index and returns the element.

• remove(value): Removes the first occurrence of a value.

Tuple Theory Questions

1. What is a tuple in , and how does it differ from a list?

• A tuple is an immutable, ordered collection.

2. How do you create a tuple in ? Provide examples.


Example:

my_tuple = (1, 2, 3)

3. Explain tuple immutability and why it is significant.

• Tuples cannot be modified after creation, making them safer for fixed data.
4. How do you access elements in a tuple by index?
Example:

my_tuple = (10, 20, 30)

print(my_tuple[1]) # Output: 20

5. Describe how slicing works in tuples.

• Works like list slicing: [start:stop:step].

6. What are the main advantages of using a tuple over a list?

• Faster, immutable, and can be used as dictionary keys.

7. How do you check if an item exists in a tuple?

• Use in.
Example:

my_tuple = (1, 2, 3)

print(2 in my_tuple) # Output: True

8. Explain how to use tuples for multiple assignments in .


Example:

a, b, c = (1, 2, 3)

9. What is tuple packing and unpacking? Provide examples.


Example:

# Packing
my_tuple = 1, 2, 3

# Unpacking

x, y, z = my_tuple

10. Can a tuple contain mutable elements, such as lists? Explain.

• Yes, but the mutable element itself can change.


Example:

my_tuple = (1, [2, 3])

my_tuple[1].append(4)

print(my_tuple) # Output: (1, [2, 3, 4])

Dictionary Theory Questions

1. What is a dictionary in , and how is it different from lists and tuples?

• A dictionary is an unordered collection of key-value pairs.

• Keys must be unique and immutable, while values can be of any data type.

• Unlike lists and tuples, dictionaries allow for quick lookup using keys instead of indices.

2. Describe how to create a dictionary in . Provide examples.


Example:

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

3. Explain the concept of key-value pairs in a dictionary.

• Each element in a dictionary is stored as a pair, where the key is used to uniquely identify the
value.
Example:
my_dict = {"name": "Alice"}

print(my_dict["name"]) # Output: Alice

4. How do you access values in a dictionary using keys?


Example:

my_dict = {"name": "Alice"}

print(my_dict["name"]) # Output: Alice

5. What happens if you try to access a key that does not exist in a dictionary?

• A KeyError is raised.
Example:

my_dict = {"name": "Alice"}

# print(my_dict["age"]) # Raises KeyError

6. Describe how to add and update elements in a dictionary.

• Use the key to add or update a value.


Example:

my_dict = {"name": "Alice"}

my_dict["age"] = 25 # Adding a new key-value pair

my_dict["name"] = "Bob" # Updating a value

7. How can you delete elements from a dictionary?

• Use del or pop().


Example:
my_dict = {"name": "Alice", "age": 25}

del my_dict["age"] # Removes the key-value pair for "age"

8. What is the difference between pop() and popitem() in dictionaries?

• pop(key): Removes the specified key-value pair and returns the value.

• popitem(): Removes and returns the last inserted key-value pair as a tuple.

9. Explain the purpose of the keys(), values(), and items() methods in a dictionary.

• keys(): Returns all keys in the dictionary.

• values(): Returns all values in the dictionary.

• items(): Returns all key-value pairs as tuples.

10. How can you check if a key exists in a dictionary?

• Use the in keyword.


Example:

my_dict = {"name": "Alice"}

print("name" in my_dict) # Output: True

11. What is dictionary comprehension, and how is it used?

• A concise way to create dictionaries.


Example:

squared = {x: x**2 for x in range(5)}

print(squared) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

12. Explain the difference between shallow and deep copies of a dictionary.

• Shallow copy (copy()): Copies references to nested objects.

• Deep copy (deepcopy()): Creates independent copies of all objects.


13. How do you merge two dictionaries in ?

• Use update() or {**dict1, **dict2}.


Example:

dict1 = {"a": 1}

dict2 = {"b": 2}

dict1.update(dict2)

print(dict1) # Output: {'a': 1, 'b': 2}

14. Describe how to iterate over a dictionary’s keys, values, and items.
Example:

my_dict = {"name": "Alice", "age": 25}

for key in my_dict:

print(key) # Iterates over keys

for value in my_dict.values():

print(value) # Iterates over values

for key, value in my_dict.items():

print(key, value) # Iterates over key-value pairs

15. What is the significance of hashable keys in a dictionary?

• Keys must be hashable (immutable and unique) to ensure efficient lookups.

16. Can dictionary keys be mutable? Explain why or why not.

• No, keys must be immutable (e.g., strings, numbers, or tuples) to maintain their hash value.

17. How do you clear all elements from a dictionary?

• Use clear().
Example:
my_dict = {"name": "Alice"}

my_dict.clear()

print(my_dict) # Output: {}

18. What is the purpose of the get() method in a dictionary, and how does it differ from direct key
access?

• get() retrieves a value by key, returning a default value if the key does not exist instead of
raising a KeyError.
Example:

my_dict = {"name": "Alice"}

print(my_dict.get("age", "Not Found")) # Output: Not Found

Nested Dictionaries and Applications

1. Explain how nested dictionaries work and how to access nested values.

• Nested dictionaries are dictionaries within dictionaries.

• Access nested values using a chain of keys.


Example:

nested_dict = {

"person1": {"name": "Alice", "age": 25},

"person2": {"name": "Bob", "age": 30}

print(nested_dict["person1"]["name"]) # Output: Alice

2. What are some common applications of dictionaries in programming?

• Data Storage: Storing structured data, such as user profiles or configuration settings.

• Frequency Counting: Counting occurrences of elements in datasets.


• Lookup Tables: Mapping keys to values for quick retrieval.

• JSON Parsing: Working with data from APIs or files.

• Graph Representation: Representing adjacency lists for graphs.

Functions in

3. What is a function in Python, and why is it used?

• A function is a reusable block of code designed to perform a specific task.

• Why use it? To enhance modularity, reusability, and readability of code.

4. Describe the syntax of defining a function in with an example.


Syntax:

def function_name(parameters):

# function body

return value

Example:

def greet(name):

return f"Hello, {name}!"

5. What is the purpose of the return statement in a function?

• The return statement is used to send a value back to the caller.

6. Explain the difference between print() and return in a function.

• print(): Displays output to the console.

• return: Passes a result back to the caller for further use.

7. What are arguments and parameters in a function?


• Parameters: Variables defined in the function signature.

• Arguments: Values passed to the function during the call.


Example:

def add(a, b): # a, b are parameters

return a + b

add(5, 3) # 5, 3 are arguments

8. How does handle variable scope within functions (local vs. global scope)?

• Variables inside a function are local by default.

• Use global keyword to modify global variables within a function.

9. What is function overloading, and does support it?

• Function overloading allows multiple functions with the same name but different
parameters.

• does not directly support overloading but can achieve similar behavior using default
arguments or *args.

10. How do anonymous functions (lambda functions) work with map(), filter(), and reduce()?

• Lambda functions are single-line, unnamed functions.

• Examples:

o map: Apply a function to each element of an iterable.

result = list(map(lambda x: x**2, [1, 2, 3]))

o filter: Filter elements based on a condition.

result = list(filter(lambda x: x % 2 == 0, [1, 2, 3]))

o reduce (from functools): Combine elements into a single value.


from functools import reduce

result = reduce(lambda x, y: x + y, [1, 2, 3])

11. What is a lambda function, and how does it differ from a regular function?

• Lambda functions are anonymous and defined using lambda keyword.

• They are concise and lack def or multiple statements.

12. When would you use a lambda function over a standard function?

• When a small, throwaway function is needed, typically for one-liners.

13. How do you call a function in , and what does function calling mean?

• Function calling involves executing a function by its name and passing arguments.
Example:

greet("Alice")

14. What is a recursive function? Provide an example.

• A function that calls itself.


Example:

def factorial(n):

if n == 1:

return 1

return n * factorial(n - 1)

Classes and Objects

15. What is a class in , and why is it used?


• A blueprint for creating objects. It defines attributes and methods.

• Used for Object-Oriented Programming (OOP).

16. Explain the concept of an object in .

• An object is an instance of a class. It represents real-world entities.

17. What is the difference between a class and an object?

• Class: Blueprint for objects.

• Object: Instance of a class with actual data.

18. How do you define a class in ? Provide an example.


Example:

class Person:

def __init__(self, name):

self.name = name

19. What are attributes in a class, and how are they defined?

• Variables defined within a class to store data.


Example:

class Car:

wheels = 4 # Attribute

20. What are methods in a class, and how do they differ from functions?

• Methods are functions defined within a class that act on object data.

21. Describe the purpose of the __init__ method in a class.

• It initializes object attributes.


22. How do you create an instance (object) of a class in ?
Example:

person = Person("Alice")

23. Explain the concept of instance variables vs. class variables.

• Instance Variables: Unique to each object.

• Class Variables: Shared across all objects.

24. How do you access and modify attributes of an object?


Example:

person.name = "Bob"

25. What is the purpose of the self keyword in a class?

• Refers to the current instance of the class.

26. What are class methods and static methods, and how do they differ?

• Class Methods: Operate on class variables. Use @classmethod.

• Static Methods: Do not depend on class or instance data. Use @staticmethod.

27. Explain how to use decorators @classmethod and @staticmethod in a class.


Example:

class MyClass:

@classmethod

def class_method(cls):

pass
@staticmethod

def static_method():

pass

Deleting Attributes or Methods in an Object

1. How can you delete an attribute or method in an object?

• Use the del keyword to delete attributes or methods of an object.


Example:

class Person:

def __init__(self, name):

self.name = name

p = Person("Alice")

del p.name # Deletes the 'name' attribute

2. Explain how classes promote modularity and code reusability.

• Classes group related data and functionality into a single unit, making code more organized.

• They allow reusability through inheritance and polymorphism.

Constructors and Polymorphism

3. What is the purpose of a constructor, and how is it defined in ?

• Purpose: Initializes an object’s attributes when the object is created.

• Syntax: Defined using the __init__() method.


Example:

class Person:

def __init__(self, name):


self.name = name

4. What is polymorphism in , and why is it useful?

• Definition: Polymorphism allows a single interface to represent different underlying forms


(data types or classes).

• Usefulness: Enables flexibility and integration of different data types.

5. Explain how polymorphism is implemented in .

• Polymorphism is implemented through:

o Duck typing: If an object behaves like a specific type, it is treated as that type.

o Method overriding: Redefining methods in derived classes.

o Operator overloading: Defining operators for custom behavior.

6. What is method overloading, and does support it?

• Definition: Having multiple methods with the same name but different parameters.

• does not directly support method overloading but can simulate it using default parameters
or variable-length arguments.
Example:

class Calculator:

def add(self, a, b=0):

return a + b

7. What is method overriding in , and how does it work?

• Definition: A derived class provides a new implementation for a method from the base class.

• How it works: The method in the derived class has the same name as in the base class.
Example:

class Parent:

def show(self):
print("Parent method")

class Child(Parent):

def show(self):

print("Child method")

8. How does achieve polymorphism without explicit method overloading?

• Using duck typing and dynamic typing.

• Functions and methods accept various data types without strict parameter signatures.

9. Explain how polymorphism works with functions and objects.

• Functions: Accept any object as long as it supports required operations.


Example:

def add(x, y):

return x + y # Works for integers, strings, lists, etc.

• Objects: Base-class references can call methods of derived classes.

10. What is operator overloading, and how can it be achieved in ?

• Definition: Customizing the behavior of operators for user-defined classes.

• How: Use special methods (e.g., __add__, __sub__).


Example:

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)


Polymorphism and Inheritance

11. Provide examples of polymorphism with classes and inheritance.


Example:

class Animal:

def sound(self):

pass

class Dog(Animal):

def sound(self):

return "Bark"

class Cat(Animal):

def sound(self):

return "Meow"

for animal in [Dog(), Cat()]:

print(animal.sound())

12. Explain the difference between polymorphism and inheritance.

• Polymorphism: Multiple forms of a method or operation.

• Inheritance: A class inherits attributes and methods from another class.

Abstraction

13. What is abstraction in object-oriented programming?

• Abstraction hides implementation details and only shows essential features.


14. How does abstraction help in simplifying complex systems?

• Focuses on relevant data and operations, improving clarity and reducing complexity.

15. What are abstract classes, and how are they defined in ?

• Classes with at least one abstract method (method without implementation).

• Defined using abc module.


Example:

from abc import ABC, abstractmethod

class Animal(ABC):

@abstractmethod

def sound(self):

pass

16. What are the key differences between abstraction and encapsulation?

• Abstraction: Hides complexity; focuses on "what" an object does.

• Encapsulation: Hides internal details; focuses on "how" it is achieved.

Inheritance

17. What is inheritance in , and why is it important?

• Inheritance allows one class (derived) to inherit attributes and methods of another class
(base).

• Importance: Promotes reusability and extensibility.

18. Explain how inheritance allows code reuse.

• Reuse base class methods and attributes in derived classes without rewriting code.

19. What is a base class (or superclass) and a derived class (or subclass)?

• Base class: Parent class.


• Derived class: Child class inheriting from the base.

20. Can private attributes be inherited in ? Explain.

• Private attributes (prefixed with __) are not directly inherited but can be accessed through
name mangling.

21. What is the purpose of overriding methods in inheritance?

• To customize behavior for derived classes.

22. What are the advantages of using inheritance in OOP?

• Reusability.

• Maintainability.

• Extensibility.

23. Explain how to use inheritance to extend the functionality of a class.


Example:

class Parent:

def greet(self):

return "Hello!"

class Child(Parent):

def greet(self):

return super().greet() + " How are you?"

Encapsulation

24. What is encapsulation in ?

• Bundling data and methods into a single unit while restricting direct access to internal
components.
25. What is the difference between public, protected, and private attributes?

• Public: Accessible everywhere.

• Protected: Accessible within the class and its subclasses (prefix _).

• Private: Accessible only within the class (prefix __).

26. How do you define a private attribute in a class?

• Use a double underscore (__).

27. What is name mangling, and how does it work with private attributes?

• Name mangling changes the attribute name to include the class name.
Example:

class MyClass:

__private = 42

print(MyClass._MyClass__private) # Access private attribute

28. Explain how getter and setter methods provide encapsulation.

• Control attribute access and modification through dedicated methods.

29. What is the difference between encapsulation and abstraction?

• Encapsulation: Hides data.

• Abstraction: Hides implementation details.

Inheritance and Subclasses

30. How do you create a subclass in ?


Syntax:

class SubClass(ParentClass):
pass

31. What is the purpose of the super() function in inheritance?

• Access methods of the base class.

32. Explain single inheritance and multiple inheritance in .

• Single inheritance: Derived class inherits from one base class.

• Multiple inheritance: Derived class inherits from multiple base classes.

33. What is the difference between single-level and multi-level inheritance?

• Single-level: One level of inheritance.

• Multi-level: Chain of inheritance.


Example:

class A:
pass

class B(A):
pass

class C(B):
pass

You might also like