Question Bank Python BCA PDF
Question Bank Python BCA PDF
2. Name two basic data types in Python. Two basic data types in Python are integer (int) and
string (str). Integers represent whole numbers like 5 or -10, while strings represent text data
enclosed in quotes like "Hello".
3. What symbol is used for comments in Python? The hash symbol (#) is used for single-line
comments in Python. Everything after the # symbol on that line is ignored by the Python interpreter.
4. Mention any one immutable data type in Python. Tuple is an immutable data type in Python.
Once created, you cannot change, add, or remove elements from a tuple, making it different from
lists which are mutable.
5. What function is used to take input from the user? The input() function is used to take input
from the user. It reads a line from the user and returns it as a string.
6. Write the syntax for a multi-line statement in Python. The backslash () is used to continue a
statement on the next line. For example: total = first_number + second_number
+ third_number. Alternatively, statements inside parentheses, brackets, or braces can span
multiple lines naturally.
7. What keyword is used to de ne a variable in Python? Python does not use any speci c
keyword to de ne a variable. Variables are created simply by assigning a value to a name, such as x
= 10 or name = "John".
8. Name any two built-in functions in Python. Two built-in functions in Python are print() and
len(). The print() function displays output on the screen, while len() returns the number of items in
an object like a string or list.
9. What will be the output of type("Hello")? The output will be <class 'str'>. The type()
function returns the data type of the given object, and "Hello" is a string, so it shows the string
class.
10. What does int("123") return? It returns the integer value 123. The int() function converts the
string "123" into its numeric integer equivalent.
11. Name a method used to convert a string to lowercase. The lower() method converts a string
to lowercase. For example, "HELLO".lower() returns "hello".
12. Write one example of an arithmetic operator. The addition operator (+) is an arithmetic
operator. For example, 5 + 3 equals 8. Other arithmetic operators include subtraction (-),
multiplication (*), and division (/).
fi
fi
fi
fi
13. How do you nd the length of a string in Python? Use the len() function to nd the length of
a string. For example, len("Hello") returns 5, which is the number of characters in the string.
14. Which operator is used for exponentiation in Python? The double asterisk () operator is
used for exponentiation. For example, 23 equals 8, which means 2 raised to the power of 3.
15. What does the id() function return? The id() function returns the unique identity (memory
address) of an object. Every object in Python has a unique identi er that remains constant during its
lifetime.
16. De ne a container data type. A container data type is a data type that can hold multiple values
or objects. Examples include lists, tuples, dictionaries, and sets, which can store collections of data
rather than just single values.
17. What is the output of print("A" + "B")? The output is "AB". The + operator concatenates
(joins) two strings together, combining "A" and "B" into a single string.
18. Which method returns the index of a substring? The nd() method returns the index of a
substring. For example, "Hello". nd("e") returns 1, which is the position where "e" rst appears in
the string.
19. Write the syntax for a formatted print statement. The syntax is print(f"text
{variable}") using f-strings. For example, print(f"Hello {name}") where name is
a variable. This allows you to embed variables directly into strings.
20. Mention one difference between is and ==. The == operator compares values for equality,
while the is operator checks if two variables refer to the same object in memory. Two variables can
have equal values but be different objects.
21. Name a string method that checks if a string is alphanumeric. The isalnum() method checks
if a string contains only alphanumeric characters (letters and numbers). It returns True if all
characters are letters or digits, False otherwise.
22. What is the output of "hello".capitalize()? The output is "Hello". The capitalize() method
converts the rst character to uppercase and makes all other characters lowercase.
23. What function returns the ASCII value of a character? The ord() function returns the ASCII
value of a character. For example, ord('A') returns 65, which is the ASCII code for the letter A.
24. What is the use of \n in a string? The \n is an escape sequence that represents a newline
character. It moves the cursor to the beginning of the next line when the string is printed.
25. Mention a mutable data type in Python. List is a mutable data type in Python. You can
change, add, or remove elements from a list after it has been created, unlike immutable types such
as tuples.
26. Write one example of a type conversion function. The str() function is a type conversion
function. For example, str(123) converts the integer 123 to the string "123".
27. What is a keyword in Python? A keyword is a reserved word that has a special meaning in
Python and cannot be used as a variable name. Examples include if, else, for, while, def, and class.
fi
fi
fi
fi
fi
fi
fi
fi
28. How do you import a module named math? Use the statement import math to import
the math module. This makes all functions and constants from the math module available for use in
your program.
29. What is the default separator used by print() function? The default separator is a single
space (" "). When printing multiple values, the print() function automatically separates them with
spaces unless speci ed otherwise.
30. What does input() return by default? The input() function returns a string by default. Even if
the user enters numbers, input() treats the data as text, so you need to convert it using int() or oat()
if you want numeric values.
1. Name the two main types of loops in Python. The two main types of loops in Python are the for
loop and the while loop. The for loop is used when you know how many times you want to repeat
something or when iterating through a collection like a list. The while loop continues executing as
long as a speci ed condition remains true, making it useful when you don't know exactly how many
iterations you'll need.
2. What is the use of break statement? The break statement is used to exit or terminate a loop
prematurely when a certain condition is met. When Python encounters a break statement inside a
loop, it immediately stops executing the loop and moves to the next statement after the loop,
regardless of whether the loop's original condition is still true.
3. What keyword is used for conditional branching? The if keyword is used for conditional
branching in Python. It allows your program to make decisions by executing different blocks of
code based on whether certain conditions are true or false. You can extend this with elif for
additional conditions and else for a default action.
4. De ne a list in Python. A list is an ordered, mutable collection of items that can store multiple
values of different data types in a single variable. Lists are created using square brackets, like [1, 2,
3] or ["apple", "banana", "cherry"]. Since lists are mutable, you can change, add, or remove
elements after creating them.
5. What is the output of 5 > 3 and 2 < 1? The output is False. This expression uses the logical and
operator, which requires both conditions to be true for the entire expression to be true. While 5 > 3
is true, 2 < 1 is false, so the complete expression evaluates to false.
6. Mention any one function that returns Boolean values from a sequence. The all() function
returns Boolean values from a sequence. It returns True if all elements in the sequence are true (or if
the sequence is empty), and False if any element is false. For example, all([True, True, False])
returns False.
fi
fi
fi
fl
7. What keyword is used to skip an iteration? The continue keyword is used to skip the current
iteration of a loop and move directly to the next iteration. When Python encounters continue, it
stops executing the remaining code in the current loop cycle and jumps back to the beginning of the
loop for the next iteration.
8. How do you de ne an empty set? You de ne an empty set using the set() function, like this:
empty_set = set(). You cannot use empty curly braces {} because that creates an empty dictionary,
not a set. This is an important distinction that often confuses beginners.
9. Write one built-in method for lists. The append() method is a built-in method for lists. It adds a
single element to the end of a list. For example, if you have a list called numbers = [1, 2, 3], then
numbers.append(4) will modify the list to [1, 2, 3, 4].
10. Which data structure is immutable: list or tuple? Tuple is immutable. Once you create a
tuple, you cannot change its contents - you cannot add, remove, or modify elements. Lists, on the
other hand, are mutable, meaning you can freely modify their contents after creation. This
immutability makes tuples useful for storing data that shouldn't change.
11. What function is used to get keys from a dictionary? The keys() method is used to get all
keys from a dictionary. It returns a view object that displays all the keys in the dictionary. For
example, if you have a dictionary called student = {"name": "John", "age": 20}, then student.keys()
will return dict_keys(["name", "age"]).
12. What operator is used to check membership? The in operator is used to check membership in
Python. It returns True if a speci ed value is found in a sequence (like a list, tuple, string, or set)
and False if it's not found. For example, "a" in "apple" returns True.
13. What is the result of not False? The result is True. The not operator is a logical operator that
reverses the Boolean value of its operand. Since False is the opposite of True, applying not to False
gives you True.
14. What is the output of len([1, 2, 3])? The output is 3. The len() function counts the number of
elements in the list [1, 2, 3], which contains three integers, so it returns 3.
15. Which loop runs when the condition is true? The while loop runs when the condition is true.
It continues executing its code block repeatedly as long as the speci ed condition evaluates to true.
Once the condition becomes false, the loop stops executing.
16. De ne a tuple. A tuple is an ordered, immutable collection of items that can store multiple
values in a single variable. Tuples are created using parentheses, like (1, 2, 3) or ("apple", "banana",
"cherry"). Unlike lists, once you create a tuple, you cannot change its contents, making it useful for
storing data that should remain constant.
18. Name a built-in function used with sets. The len() function is a built-in function commonly
used with sets. It returns the number of elements in a set. For example, len({1, 2, 3, 4}) returns 4,
telling you how many unique elements the set contains.
fi
fi
fi
fi
fi
19. How do you append an item to a list? You use the append() method to add an item to the end
of a list. The syntax is list_name.append(item). For example, if you have fruits = ["apple",
"banana"], then fruits.append("orange") will modify the list to ["apple", "banana", "orange"].
20. What is the output of all([True, False, True])? The output is False. The all() function returns
True only if all elements in the sequence are true. Since the list contains False as one of its
elements, the entire expression evaluates to False, even though two of the three elements are True.
21. How do you create a dictionary in Python? You create a dictionary using curly braces with
key-value pairs separated by colons. For example, student = {"name": "John", "age": 20, "grade":
"A"}. You can also create an empty dictionary using empty curly braces {} or the dict() function.
22. Write the syntax for list comprehension. The syntax for list comprehension is [expression for
item in iterable]. For example, [x**2 for x in range(5)] creates a list of squares [0, 1, 4, 9, 16]. You
can also add conditions like [x for x in range(10) if x % 2 == 0] to lter elements.
23. Name the keyword used to create an empty block. The pass keyword is used to create an
empty block in Python. It serves as a placeholder when you need a statement syntactically but don't
want to execute any code. For example, you might use it in an if statement or function de nition
that you plan to complete later.
24. Which method removes the last item from a list? The pop() method removes and returns the
last item from a list. For example, if numbers = [1, 2, 3, 4], then numbers.pop() will remove 4 and
return it, leaving the list as [1, 2, 3].
25. Mention a method to update a dictionary. The update() method is used to update a dictionary.
It can add new key-value pairs or modify existing ones. For example, student.update({"age": 21,
"city": "New York"}) will update the age and add a new city key to the student dictionary.
26. How do you remove duplicates from a list? You can remove duplicates from a list by
converting it to a set and then back to a list. For example, unique_list = list(set(original_list)). The
set automatically removes duplicates because sets only contain unique elements, though this method
doesn't preserve the original order.
27. What is a nested loop? A nested loop is a loop inside another loop. The inner loop completes
all its iterations for each iteration of the outer loop. For example, a nested for loop might be used to
process a two-dimensional list where the outer loop handles rows and the inner loop handles
columns.
28. What does the any() function do? The any() function returns True if at least one element in a
sequence is true, and False if all elements are false or if the sequence is empty. For example,
any([False, True, False]) returns True because at least one element is True.
29. Write one example of a for loop. Here's an example of a for loop: for i in range(5): print(i).
This loop will print numbers 0 through 4, executing the print statement ve times. The range(5)
creates a sequence of numbers from 0 to 4.
30. How do you access a value from a dictionary using a key? You access a value from a
dictionary using square brackets with the key name, like dictionary_name[key]. For example, if
student = {"name": "John", "age": 20}, then student["name"] returns "John". You can also use the
get() method, like student.get("name"), which is safer as it won't raise an error if the key doesn't
exist.
fi
fi
fi
Unit III: Functions, Modules, and Packages
1. What keyword is used to de ne a function in Python? The def keyword is used to de ne a
function in Python.
2. What is the purpose of return statement? The return statement sends a value back from a
function and exits the function immediately.
3. De ne a lambda function. A lambda function is a small anonymous function that can have
multiple arguments but only one expression.
4. Write one example of a built-in function. The max() function nds the largest value from given
arguments, like max(5, 2, 8) returns 8.
*5. What is the use of args? *args allows a function to accept any number of positional arguments
as a tuple.
6. Which function is used to apply a function to all elements in a list? The map() function
applies a given function to all elements in an iterable.
7. How do you import a speci c function from a module? Use from module_name import
function_name syntax.
8. Name one recursive function in mathematics. The factorial function is a classic recursive
function where n! = n × (n-1)!.
9. What is the output of map()? The map() function returns a map object, which must be
converted to a list to see actual results.
10. What is the main module in Python? The main module is the module being run directly,
where name equals "main".
11. Write the syntax to call a function. The syntax is function_name(arguments) with parentheses
required to execute the function.
12. What does lter() return? The lter() function returns a lter object containing elements that
pass a given test.
13. Which function is used to reduce a list to a single value? The reduce() function from
functools module reduces a list to a single value.
14. Name a built-in module in Python. The math module provides mathematical functions and
constants.
15. What is the le extension for Python modules? Python modules use the .py le extension.
17. How do you import all functions from a module? Use from module_name import * to import
all functions from a module.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
18. What is the use of init.py le? The init.py le marks a directory as a package and can contain
initialization code.
19. Name the function used for anonymous functions. The lambda function creates anonymous
functions in Python.
20. What is a default argument in a function? A default argument has a pre-assigned value used
when no argument is provided during function call.
21. What is the output of len("abc")? The output is 3, counting the three characters in the string.
22. What does print(name) output when a le is run directly? It outputs "main" when the le is
executed directly.
23. Mention a difference between map() and lter(). map() transforms all elements while lter()
selects elements based on a condition.
24. De ne a user-de ned function. A user-de ned function is created by the programmer using the
def keyword for speci c tasks.
25. How do you pass keyword arguments to a function? Pass keyword arguments using
parameter_name=value syntax in the function call.
26. Write one use of recursion. Calculating Fibonacci numbers where each number equals the sum
of two preceding numbers.
27. What is the use of **kwargs? **kwargs allows a function to accept any number of keyword
arguments as a dictionary.
28. Write one line to de ne a function that returns square of a number. def square(x): return x
** 2
29. How do you create a module? Create a module by writing Python code in a .py le and saving
it.
30. What does help() do in Python? The help() function displays documentation and help
information about Python objects and functions.
2. De ne an object in Python. An object is an instance of a class that contains data (attributes) and
methods (functions).
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
3. What is the purpose of init method? The init method is a constructor that initializes an object
when it is created.
4. What does OOP stand for? OOP stands for Object-Oriented Programming.
5. Mention one feature of inheritance. Code reusability is a key feature where child classes inherit
properties and methods from parent classes.
6. How do you handle exceptions in Python? Use try-except blocks to handle exceptions and
prevent program crashes.
8. Name the keyword used to de ne a constructor. The init method serves as the constructor in
Python classes.
9. What does nally block do? The nally block executes code regardless of whether an exception
occurs or not.
10. What keyword is used to create an exception? The raise keyword is used to manually create
and throw an exception.
12. What keyword is used to inherit a class? Python uses class ChildClass(ParentClass): syntax
where parentheses indicate inheritance.
13. What is encapsulation? Encapsulation is binding data and methods together within a class and
controlling access to them.
14. Mention one difference between public and private members. Public members are accessible
from outside the class, while private members (pre xed with __) are not directly accessible.
15. What is the output of open(" le.txt") if le exists? It returns a le object that can be used to
read from or write to the le.
17. What does with open(" le.txt") as f: do? It opens a le and automatically closes it when the
block ends, ensuring proper resource management.
18. What function is used to read a le line by line? The readline() method reads one line at a
time from a le.
19. What method is used to write to a le? The write() method is used to write data to a le.
20. Name the mode used to append data to a le. The 'a' mode opens a le for appending data at
the end.
21. Write one example of single inheritance. class Animal: pass followed by class Dog(Animal):
pass shows Dog inheriting from Animal.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
22. What is exception handling? Exception handling is a mechanism to catch and handle runtime
errors gracefully without crashing the program.
23. Name a built-in exception class. ValueError is a built-in exception raised when a function
receives an inappropriate argument value.
24. What is the use of readline()? The readline() method reads a single line from a le and returns
it as a string.
25. Mention one le mode for writing. The 'w' mode opens a le for writing, creating a new le or
overwriting existing content.
26. What is the output of f.read()? The read() method returns the entire content of the le as a
single string.
27. How do you de ne a user-de ned exception? Create a class that inherits from the Exception
class: class MyError(Exception): pass
28. Write one bene t of OOP. Code reusability allows writing code once and using it multiple
times through inheritance and composition.
29. Name a feature of polymorphism. Method overriding allows different classes to have methods
with the same name but different implementations.
30. What happens if an exception is not handled? The program terminates abruptly and displays
an error message showing the exception details.
————————————————————————————————————————
————————————————————————————————————————
————————————————————————————————————————
9. Which of the following functions can accept input from users in Python?
a) read()
b) gets()
fl
fi
c) scanf()
d) input()
Answer: d
26. Which function can be used to get string input from the console?
a) read()
b) input()
c) gets()
d) scan()
Answer: b
15. Which function is used to loop through both key and value in a dictionary?
a) keys()
b) values()
c) items()
d) get()
Answer: c) items()
16. Which of the following methods will remove all elements from a dictionary?
a) del dict
b) dict.remove()
c) dict.clear()
d) dict.pop()
Answer: c) dict.clear()
25. Which loop runs at least once in many languages but not in Python?
a) while
b) for
c) do-while
d) None
Answer: c) do-while
10. What is the default return value of a function that doesn’t return anything?
a) 0
b) None
c) Unde ned
d) Null
Answer: b) None
12. Which is the correct syntax for a function with arbitrary arguments?
a) def func(args):
b) def func(args):
c) def func(args):
d) def func[*args]:
*Answer: a) def func(args):
16. How can you import only a speci c function from a module?
a) import module.function
b) from module import function
c) using module.function
d) def import function from module
Answer: b) from module import function
18. Which of these will execute a module only if it’s run as the main script?
a) if main == "name":
b) if name == "main":
c) if main == run:
d) if start():
Answer: b) if name == "main":
21. Which function returns a list of all local variables inside a function?
a) vars()
b) dir()
c) locals()
d) globals()
Answer: c) locals()
fi
fi
fi
fi
22. How do you de ne a function with a default argument?
a) def func(x = 5):
b) def func(=5 x):
c) def func(default=5):
d) def func(5=x):
Answer: a) def func(x = 5):
25. Which function will allow calling another function inside it recursively?
a) call()
b) return self()
c) A function calling itself
d) Nested function only
Answer: c) A function calling itself
28. What is the result of calling a function with fewer arguments than expected?
a) None
b) Default is assumed
c) Error
d) Zero is used
Answer: c) Error
20. Which mode is used to append content to a le without removing existing content?
a) 'w'
b) 'r'
c) 'a'
d) 'rw'
Answer: c) 'a'
22. What will happen if open() is called on a le that does not exist in 'r' mode?
a) File is created
b) File is truncated
c) FileNotFoundError
d) New le opened
Answer: c) FileNotFoundError
————————————————————————————————————————
————————————————————————————————————————
Python Basics
1. What are Python keywords? Give any four examples.
- *Answer:* Keywords are reserved words with predefined
meanings in Python. Examples: `if`, `else`, `for`, `while`.
Strings
9. How are strings accessed in Python? Explain with an example.
- *Answer:* Using indexing (`str[0]`) or slicing (`str[1:5]`).
Example: `"Python"[1]` → `'y'`.
17. Explain the use of `//`, `%`, and `` operators with examples.
- *Answer:*
- `//` (Floor division): `7 // 2` → `3`
- `%` (Modulus): `7 % 2` → `1`
- `` (Exponentiation): `2 3` → `8`
Strings
26. How do you reverse a string in Python? Provide two methods.
- *Answer:*
```python
s = "hello"
print(s[::-1]) # Slicing
print(''.join(reversed(s))) # reversed() + join
```
### Unit II: Control Structures and Data Structures – Short Answer
Questions (2 Marks)
Control Structures
16. What are logical operators in Python? Give examples.
- *Answer:* `and`, `or`, `not`. Example: `if (x > 0 and x <
10)`.
Data Structures
21. How do you create a list in Python? Give an example.
- *Answer:* Using square brackets. Example: `my_list = [1, 2,
3]`.
19. How does the `range()` function work? Provide three use cases.
- *Answer:* Generates a sequence of numbers. Examples:
- `range(5)` → `0, 1, 2, 3, 4`
- `range(1, 6, 2)` → `1, 3, 5`
- `list(range(3))` → `[0, 1, 2]`
Data Structures
21. How do you remove duplicates from a list?
- *Answer:* Convert to a set and back to a list:
```python
lst = [1, 2, 2, 3]
unique = list(set(lst)) # [1, 2, 3]
```
30. What is the output of `tuple([1, 2, 3])`? Why are tuples used
over lists?
- *Answer:* `(1, 2, 3)`. Tuples are immutable, making them
safer for fixed data.
---
### Unit III: Functions, Modules, and Packages – Short Answer
Questions (2 Marks)
Functions
1. What is a lambda function in Python? Provide an example.
- *Answer:* A lambda is an anonymous function defined using the
`lambda` keyword. Example: `square = lambda x: x 2`.
Functions
16. What is the difference between positional and keyword
arguments in Python functions? Give an example of each.
- *Answer:*
- Positional arguments are passed based on their position.
Example: `func(1, 2)`
- Keyword arguments are passed with parameter names. Example:
`func(a=1, b=2)`
18. How would you write a function that accepts any number of
keyword arguments? Show with an example.
- *Answer:*
```python
def print_kwargs(kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_kwargs(name="Alice", age=25)
```
def cube(x):
return x3
```
# main.py
from mypackage.module import useful_func
print(useful_func())
```
28. How would you make a Python package installable using pip?
List the key files needed.
- *Answer:* Need `setup.py`, `__init__.py`, and optionally
`MANIFEST.in`
### Unit IV: OOP, Exception Handling, and File Handling – Short
Answer Questions (2 Marks)
Exception Handling
8. What is an exception? How is it handled in Python?
- *Answer:* An error during execution. Handled using `try`,
`except`, `finally`.
9. Differentiate between `try-except` and `try-finally`.
- *Answer:* `except` catches exceptions; `finally` always
executes, regardless of exceptions.
File Handling
12. What are the different file modes in Python?
- *Answer:* `"r"` (read), `"w"` (write), `"a"` (append),
`"r+"` (read+write).
---
class Child(Parent):
def show(self):
print("Child")
```
18. How do you implement operator overloading for the `+` operator
in Python?
- *Answer:* By defining `__add__` method:
```python
class Point:
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
```
19. What are class methods and static methods? How do they differ?
- *Answer:*
- Class methods take `cls` parameter and can modify class
state
- Static methods don't take any special parameters
class B:
pass
Exception Handling
21. How would you create a custom exception class in Python?
- *Answer:*
```python
class MyError(Exception):
pass
```
File Handling
24. How do you read a CSV file in Python? Show a basic example.
- *Answer:*
```python
import csv
with open('data.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
25. What is the difference between `'r+'` and `'w+'` file modes?
- *Answer:*
- `'r+'` opens for reading and writing (file must exist)
- `'w+'` opens for reading and writing (creates/truncates
file)
27. How would you handle large files in Python without loading
them entirely into memory?
- *Answer:* Process line by line:
```python
with open('large.txt') as f:
for line in f:
process(line)
```
3. Discuss the role of identi ers in Python and list any ve rules for naming them.
Answer: Identi ers are names for variables, functions, or classes in Python. They help
identify program elements. Rules: 1) Must start with a letter or underscore (_). 2) Can
contain letters, digits, or underscores. 3) Case-sensitive (e.g., Age ≠ age). 4) Cannot be
Python keywords. 5) No special characters like @, #.
5. Explain the concept of mutable and immutable data types in Python with examples.
Answer: Mutable data types can be changed after creation, e.g., lists (my_list = [1,
2]; my_list[0] = 3). Immutable data types cannot be modi ed, e.g., strings
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
(name = "Python"; name[0] = "J" raises an error) and tuples (t = (1,
2); t[0] = 3 fails). Mutability affects how data is manipulated in memory.
6. Describe the range of integers and oats in Python and their limitations.
Answer: Python integers have unlimited range, constrained only by system memory (e.g., x
= 10**100). Floats follow IEEE 754 double-precision, with a range of approximately
±1.8 × 10³⁰⁸. Limitations: Floats may lose precision in very large calculations or with
decimals (e.g., 0.1 + 0.2 ≠ 0.3 due to binary approximation).
10. Describe type conversion in Python with examples of implicit and explicit conversions.
Answer: Type conversion changes a variable’s type. Implicit: Done automatically, e.g., x =
5 + 2.0 results in 7.0 ( oat). Explicit: Uses functions like int(), float(),
str(). Example: x = int("10") converts string "10" to integer 10; y =
float(5) converts integer 5 to 5.0.
11. Write a short note on the print() function and its formatting options.
Answer: The print() function outputs data to the console. Formatting options include:
1) sep: Sets separator (default space), e.g., print(1, 2, sep="-") outputs 1-2.
2) end: Sets end character (default newline), e.g., print("Hi", end=" "). 3) f-
strings: print(f"Value: {x}") embeds variables.
12. Explain the role of the math module in Python with two examples.
Answer: The math module provides mathematical functions. Examples: 1)
math.sqrt(16) returns 4.0. 2) math.factorial(5) returns 120 (5!). It
includes functions like sin(), cos(), log(), and constants like math.pi.
16. Explain how to access string elements using indexing and slicing.
Answer: Indexing accesses a single character, e.g., s = "Python"; print(s[0])
outputs P. Slicing extracts a substring, e.g., s[1:4] outputs yth. Negative indexing starts
from the end, e.g., s[-1] is n.
17. Discuss the len() function and its use with strings.
Answer: The len() function returns the number of characters in a string. Example:
len("Python") returns 6. It counts all characters, including spaces and special
characters, and is used for string length validation or iteration.
18. Write a short note on the upper() and lower() string methods.
Answer: upper() converts a string to uppercase, e.g., "python".upper() returns
"PYTHON". lower() converts to lowercase, e.g., "PYTHON".lower() returns
"python". Both are non-destructive (original string unchanged) and useful for case-
insensitive comparisons.
22. Describe the use of the format() method for string formatting.
Answer: The format() method inserts values into a string’s placeholders {}. Example:
"Hi, {}".format("Alice") yields "Hi, Alice". Supports positional ({0})
and named arguments ({name}), e.g., "Age: {age}".format(age=25).
23. Write a short note on escape sequences in Python strings.
Answer: Escape sequences are special characters starting with \. Examples: \n (newline),
\t (tab), \\ (backslash), \" (quote). Example: print("Line1\nLine2") outputs
two lines. They allow formatting and inclusion of special characters.
24. Explain the input() function and its role in console input.
Answer: The input() function reads user input as a string from the console. Example:
name = input("Enter name: ") prompts and stores input. Optional prompt
text customizes the message. Use int() or float() for numeric input.
28. Write a short note on the startswith() and endswith() string methods.
Answer: startswith() checks if a string begins with a pre x, e.g.,
"Python".startswith("Py") returns True. endswith() checks for a suf x,
e.g., "Python".endswith("on") returns True. Both are case-sensitive and useful
for validation.
11. Describe looping through a list using a for loop with an example.
Answer: A for loop iterates over list elements. Example: my_list = [1, 2, 3];
for x in my_list: print(x) prints 1, 2, 3. It’s direct and readable for
processing each element sequentially.
14. Discuss the pop() and remove() methods for lists with examples.
Answer: pop() removes and returns an element by index (default: last), e.g., my_list
= [1, 2, 3]; my_list.pop(1) returns 2, list becomes [1, 3]. remove()
deletes the rst occurrence of a value, e.g., my_list.remove(1) results in [3].
18. Write a short note on the add() and update() methods for sets.
Answer: add() inserts a single element, e.g., my_set = {1, 2};
my_set.add(3) results in {1, 2, 3}. update() adds multiple elements from an
iterable, e.g., my_set.update([3, 4]) results in {1, 2, 3, 4}. Both ensure
uniqueness.
22. Explain the count() and index() methods for tuples with examples.
Answer: count() returns the number of occurrences, e.g., (1, 2, 2,
3).count(2) returns 2. index() returns the rst index of a value, e.g., (1, 2,
3).index(2) returns 1. Both are useful for tuple analysis.
28. Explain the union() and intersection() methods for sets with examples.
Answer: union() combines all elements, e.g., {1, 2}.union({2, 3}) returns
{1, 2, 3}. intersection() keeps common elements, e.g., {1,
2}.intersection({2, 3}) returns {2}. Both are useful for set operations.
29. Discuss the use of the in operator with lists, sets, and dictionaries.
Answer: The in operator checks membership. Lists: 3 in [1, 2, 3] is True. Sets:
fi
fi
fi
fi
3 in {1, 2, 3} is True. Dictionaries: Checks keys, e.g., "a" in {"a": 1} is
True. It’s fast for sets and dictionaries.
2. Describe the difference between built-in and user-de ned functions in Python.
Answer: Built-in functions are prede ned in Python, e.g., print(), len(). User-
de ned functions are created by programmers using def, e.g., def greet():
return "Hello". Built-in functions are ready-to-use; user-de ned functions are
customized for speci c tasks.
3. Discuss the syntax for de ning a user-de ned function in Python with an example.
Answer: Syntax: def function_name(parameters): statement(s).
Example: def square(num): return num * num. This de nes a function
square that takes num and returns its square, e.g., square(4) returns 16. The
return statement is optional.
12. Describe the map() function and its use with an example.
Answer: map() applies a function to all items in an iterable, returning a map object.
Example: list(map(lambda x: x**2, [1, 2, 3])) returns [1, 4, 9].
It’s used for transforming data ef ciently without explicit loops.
14. Explain the reduce() function from the functools module with an example.
Answer: reduce() applies a function cumulatively to an iterable’s items, reducing to a
single value. Example: from functools import reduce;
reduce(lambda x, y: x + y, [1, 2, 3]) returns 6. It’s used for
operations like summing or multiplying lists.
17. Describe how to import a module in Python with different import styles.
Answer: Modules are imported using import. Styles: 1) import math (whole
module). 2) from math import sqrt (speci c function). 3) import math as
m (alias). Example: m.sqrt(16) returns 4.0. Imports enable code reuse.
18. Write a short note on the import statement and its variants.
Answer: The import statement loads modules. Variants: 1) import module (basic
import). 2) from module import item (speci c import). 3) import module
as alias (aliasing). 4) from module import * (all items, avoided for clarity).
Example: import math; math.pi.
28. Explain the difference between import module and from module import
*.
Answer: import module imports the entire module, accessed as module.name.
from module import * imports all names, allowing direct use (e.g., sqrt(16)).
The latter risks name con icts and is less clear, so import module is preferred.
29. Discuss the use of the dir() function to explore module contents.
Answer: The dir() function lists a module’s attributes (functions, variables, etc.).
Example: import math; print(dir(math)) shows functions like sqrt, pi.
It’s useful for exploring module contents during development or debugging.
30. Explain how to create a simple Python program using multiple modules.
Answer: Create modules (e.g., calc.py with def add(a, b): return a +
b) and a main program (e.g., main.py: import calc; print(calc.add(2,
3))). Run main.py to output 5. Modules split code for better organization.
17. Describe the try and except blocks in Python with an example.
Answer: try contains code that might raise an exception; except handles it. Example:
try: x = 1 / 0; except ZeroDivisionError: print("Cannot
divide by zero") prints the message instead of crashing. It ensures robust error
handling.
23. Write a short note on the read() and readline() methods for le handling.
Answer: read() reads the entire le as a string, e.g., f.read(). readline() reads
one line, e.g., f.readline(). Example: f = open("file.txt", "r");
print(f.readline()) reads the rst line. They’re used for le content access.
26. Describe the difference between text and binary le modes in Python.
Answer: Text mode ("r", "w") handles strings, encoding/decoding automatically. Binary
mode ("rb", "wb") handles bytes, used for non-text les like images. Example:
open("img.jpg", "rb") reads bytes; open("text.txt", "r") reads
strings.
29. Discuss the advantages of using the with keyword for le operations.
Answer: Advantages: 1) Automatically closes les, even on errors. 2) Simpli es code (no
close() needed). 3) Ensures resource cleanup. Example: with
open("file.txt", "r") as f: print(f.read()) safely reads a le.
————————————————————————————————————————
——————————————5. CODE
—————————————————————————— —————————————
———————————————
python
# Program to check if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
2. Write a Python program to convert a temperature given in Celsius to Fahrenheit.
Answer:
fi
fi
fi
fi
fi
fi
fi
python
# Program to convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"Temperature in Fahrenheit: {fahrenheit:.2f}")
3. Write a Python program to swap two variables using a temporary variable.
Answer:
python
# Program to swap two variables using a temporary variable
a = 10
b = 20
print(f"Before swap: a = {a}, b = {b}")
temp = a
a = b
b = temp
print(f"After swap: a = {a}, b = {b}")
4. Write a Python program to swap two variables without using a temporary variable.
Answer:
python
# Program to swap two variables without a temporary variable
a = 10
b = 20
print(f"Before swap: a = {a}, b = {b}")
a, b = b, a
print(f"After swap: a = {a}, b = {b}")
5. Write a Python program to nd the largest of three numbers.
Answer:
python
# Program to find the largest of three numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
largest = max(a, b, c)
print(f"Largest number is {largest}")
6. Write a Python program to nd the sum of digits of a number.
Answer:
python
# Program to find the sum of digits of a number
num = int(input("Enter a number: "))
fi
fi
sum_digits = 0
while num > 0:
sum_digits += num % 10
num = num // 10
print(f"Sum of digits: {sum_digits}")
7. Write a Python program to check if a given string is a palindrome.
Answer:
python
# Program to check if a string is palindrome
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
8. Write a Python program to count the number of vowels in a string.
Answer:
python
# Program to count vowels in a string
s = input("Enter a string: ")
vowels = 'aeiou'
count = 0
for ch in s.lower():
if ch in vowels:
count += 1
print(f"Number of vowels: {count}")
9. Write a Python program to reverse a string.
Answer:
python
# Program to reverse a string
s = input("Enter a string: ")
print(f"Reversed string: {s[::-1]}")
10. Write a Python program to convert the last character of each word in a string to
uppercase.
Answer:
python
# Program to convert last character of each word to uppercase
s = input("Enter a sentence: ")
words = s.split()
result = []
for word in words:
if len(word) > 0:
word = word[:-1] + word[-1].upper()
result.append(word)
print(' '.join(result))
(Note: This code may not work as expected for punctuation or single-letter words; for exam
purposes, it is acceptable.)
python
# Program to print ASCII value of a character
ch = input("Enter a character: ")
print(f"ASCII value of {ch} is {ord(ch)}")
12. Write a Python program to check if a substring is present in a given string.
Answer:
python
# Program to check if substring exists in string
s = input("Enter string: ")
sub = input("Enter substring: ")
print("Substring present" if sub in s else "Substring not
present")
13. Write a Python program to remove all vowels from a string.
Answer:
python
# Program to remove vowels from a string
s = input("Enter a string: ")
vowels = 'aeiouAEIOU'
result = ''.join([ch for ch in s if ch not in vowels])
print(f"Result: {result}")
14. Write a Python program to count the number of words in a string.
Answer:
python
# Program to count words in a string
s = input("Enter a sentence: ")
words = s.split()
print(f"Number of words: {len(words)}")
15. Write a Python program to print all the indices of a substring in a string.
Answer:
python
# Program to print all indices of a substring in a string
s = input("Enter string: ")
sub = input("Enter substring: ")
indices = []
for i in range(len(s) - len(sub) + 1):
if s[i:i+len(sub)] == sub:
indices.append(i)
print(f"Indices: {indices}")
16. Write a Python program to check if two strings are anagrams.
Answer:
python
# Program to check if two strings are anagrams
s1 = input("Enter first string: ").lower()
s2 = input("Enter second string: ").lower()
if sorted(s1) == sorted(s2):
print("Anagrams")
else:
print("Not anagrams")
17. Write a Python program to nd the frequency of each character in a string.
Answer:
python
# Program to find frequency of each character in a string
s = input("Enter a string: ")
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
print("Character frequencies:")
for ch, count in freq.items():
print(f"{ch}: {count}")
18. Write a Python program to replace all occurrences of a character in a string with another
character.
Answer:
python
# Program to replace all occurrences of a character in a
string
s = input("Enter a string: ")
old = input("Enter character to replace: ")
new = input("Enter new character: ")
print(s.replace(old, new))
19. Write a Python program to print the number of digits and letters in a string.
Answer:
fi
python
# Program to count digits and letters in a string
s = input("Enter a string: ")
digits = letters = 0
for ch in s:
if ch.isdigit():
digits += 1
elif ch.isalpha():
letters += 1
print(f"Digits: {digits}, Letters: {letters}")
20. Write a Python program to print a string in a formatted manner (e.g., "Hello, {name}!
Your score is {score}.").
Answer:
python
# Program to print formatted string
name = input("Enter your name: ")
score = int(input("Enter your score: "))
print(f"Hello, {name}! Your score is {score}.")
python
# Program to print all prime numbers between two numbers
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
python
# Program to find factorial using recursion
def factorial(n):
if n == 1 or n == 0:
return 1
else:
return n * factorial(n-1)
python
# Program to check if a number is Armstrong number
num = int(input("Enter a number: "))
order = len(str(num))
temp = num
sum = 0
while temp > 0:
digit = temp % 10
sum += digit ** order
temp = temp // 10
if num == sum:
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
5. Write a Python program to print the multiplication table of a given number.
Answer:
python
# Program to print multiplication table
fi
n = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{n} x {i} = {n*i}")
6. Write a Python program to nd the sum of all elements in a list.
Answer:
python
# Program to find sum of all elements in a list
lst = list(map(int, input("Enter numbers separated by space:
").split()))
print(f"Sum of list elements: {sum(lst)}")
7. Write a Python program to nd the largest and smallest element in a list.
Answer:
python
# Program to find largest and smallest in a list
lst = list(map(int, input("Enter numbers separated by space:
").split()))
print(f"Largest: {max(lst)}, Smallest: {min(lst)}")
8. Write a Python program to remove duplicates from a list.
Answer:
python
# Program to remove duplicates from a list
lst = list(map(int, input("Enter numbers separated by space:
").split()))
unique = list(set(lst))
print(f"List without duplicates: {unique}")
9. Write a Python program to check if a list is sorted in ascending order.
Answer:
python
# Program to check if a list is sorted in ascending order
lst = list(map(int, input("Enter numbers separated by space:
").split()))
if lst == sorted(lst):
print("List is sorted in ascending order")
else:
print("List is not sorted in ascending order")
10. Write a Python program to nd the second largest number in a list.
Answer:
python
# Program to find second largest in a list
fi
fi
fi
lst = list(map(int, input("Enter numbers separated by space:
").split()))
unique = sorted(list(set(lst)), reverse=True)
if len(unique) >= 2:
print(f"Second largest: {unique[1]}")
else:
print("Not enough unique elements")
11. Write a Python program to merge two lists and sort them.
Answer:
python
# Program to merge and sort two lists
lst1 = list(map(int, input("Enter first list: ").split()))
lst2 = list(map(int, input("Enter second list: ").split()))
merged = lst1 + lst2
merged.sort()
print(f"Merged and sorted list: {merged}")
12. Write a Python program to nd the common elements between two lists.
Answer:
python
# Program to find common elements between two lists
lst1 = list(map(int, input("Enter first list: ").split()))
lst2 = list(map(int, input("Enter second list: ").split()))
common = list(set(lst1) & set(lst2))
print(f"Common elements: {common}")
13. Write a Python program to nd the union and intersection of two sets.
Answer:
python
# Program to find union and intersection of two sets
set1 = set(map(int, input("Enter first set: ").split()))
set2 = set(map(int, input("Enter second set: ").split()))
print(f"Union: {set1 | set2}")
print(f"Intersection: {set1 & set2}")
14. Write a Python program to print the rst n elements of a list using a while loop.
Answer:
python
# Program to print first n elements using while loop
lst = list(map(int, input("Enter numbers separated by space:
").split()))
n = int(input("Enter n: "))
i = 0
fi
fi
fi
print("First", n, "elements:")
while i < n and i < len(lst):
print(lst[i], end=" ")
i += 1
15. Write a Python program to count the frequency of each element in a list.
Answer:
python
# Program to count frequency of each element in a list
lst = list(map(int, input("Enter numbers separated by space:
").split()))
freq = {}
for num in lst:
freq[num] = freq.get(num, 0) + 1
print("Element frequencies:")
for num, count in freq.items():
print(f"{num}: {count}")
16. Write a Python program to create a dictionary from two lists (keys and values).
Answer:
python
# Program to create dictionary from two lists
keys = input("Enter keys separated by space: ").split()
values = list(map(int, input("Enter values separated by
space: ").split()))
if len(keys) == len(values):
d = dict(zip(keys, values))
print("Dictionary:", d)
else:
print("Number of keys and values must be equal")
17. Write a Python program to sort a dictionary by value.
Answer:
python
# Program to sort dictionary by value
d = {'a': 5, 'b': 2, 'c': 8, 'd': 1}
sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
print("Sorted dictionary:", sorted_d)
18. Write a Python program to nd the sum of all values in a dictionary.
Answer:
python
# Program to find sum of all values in a dictionary
d = {'a': 5, 'b': 2, 'c': 8, 'd': 1}
fi
print(f"Sum of values: {sum(d.values())}")
19. Write a Python program to nd the maximum and minimum values in a dictionary.
Answer:
python
# Program to find max and min values in a dictionary
d = {'a': 5, 'b': 2, 'c': 8, 'd': 1}
print(f"Maximum value: {max(d.values())}")
print(f"Minimum value: {min(d.values())}")
20. Write a Python program using list comprehension to create a list of squares of numbers
from 1 to n.
Answer:
python
# Program to create list of squares using list comprehension
n = int(input("Enter n: "))
squares = [i**2 for i in range(1, n+1)]
print("Squares:", squares)
python
# Program to find sum of all even numbers between two
integers
start = int(input("Enter the start number: "))
end = int(input("Enter the end number: "))
sum_even = 0
for num in range(start, end + 1):
if num % 2 == 0:
sum_even += num
print("Sum of even numbers:", sum_even)
2. Write a Python program to reverse a list using a while loop.
Answer:
python
# Program to reverse a list using while loop
lst = list(map(int, input("Enter list elements: ").split()))
i = len(lst) - 1
fi
fi
rev_lst = []
while i >= 0:
rev_lst.append(lst[i])
i -= 1
print("Reversed list:", rev_lst)
3. Write a Python program to merge two dictionaries and print the result.
Answer:
python
# Program to merge two dictionaries
dict1 = eval(input("Enter first dictionary (e.g., {'a':1,
'b':2}): "))
dict2 = eval(input("Enter second dictionary (e.g., {'c':3,
'd':4}): "))
merged = {**dict1, **dict2}
print("Merged dictionary:", merged)
4. Write a Python program to nd the intersection of two sets.
Answer:
python
# Program to find intersection of two sets
set1 = set(map(int, input("Enter first set: ").split()))
set2 = set(map(int, input("Enter second set: ").split()))
print("Intersection:", set1 & set2)
5. Write a Python program using list comprehension to lter out all odd numbers from a list.
Answer:
python
# Program to filter out odd numbers using list comprehension
lst = list(map(int, input("Enter list elements: ").split()))
filtered = [num for num in lst if num % 2 == 0]
print("Even numbers:", filtered)
6. Write a Python program to implement the bubble sort algorithm on a list.
Answer:
python
# Program to implement bubble sort
lst = list(map(int, input("Enter list elements: ").split()))
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
print("Sorted list:", lst)
fi
fi
7. Write a Python program to count the frequency of each element in a tuple.
Answer:
python
# Program to count frequency of elements in a tuple
tup = tuple(map(int, input("Enter tuple elements:
").split()))
freq = {}
for num in tup:
freq[num] = freq.get(num, 0) + 1
print("Element frequencies:", freq)
8. Write a Python program to remove duplicates from a list while preserving the order.
Answer:
python
# Program to remove duplicates preserving order
lst = input("Enter list elements: ").split()
unique = []
for item in lst:
if item not in unique:
unique.append(item)
print("List after removing duplicates:", unique)
9. Write a Python program to nd the largest element in a list using a function.
Answer:
python
# Program to find largest element using a function
def find_max(lst):
return max(lst)
python
# Program to print all prime numbers in a range using a
function
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
fi
return True
python
# Program to create dictionary from two lists
keys = input("Enter keys separated by space: ").split()
values = input("Enter values separated by space: ").split()
if len(keys) == len(values):
d = dict(zip(keys, values))
print("Dictionary:", d)
else:
print("Number of keys and values must be equal")
12. Write a Python program to print all key-value pairs of a dictionary using a for loop.
Answer:
python
# Program to print all key-value pairs of a dictionary
d = eval(input("Enter dictionary (e.g., {'a':1, 'b':2}): "))
print("Key-value pairs:")
for key, value in d.items():
print(key, ":", value)
13. Write a Python program to implement a stack using a list with push and pop operations.
Answer:
python
# Program to implement stack using list
stack = []
while True:
print("\n1. Push\n2. Pop\n3. Exit")
ch = int(input("Enter choice: "))
if ch == 1:
item = input("Enter item to push: ")
stack.append(item)
print("Stack:", stack)
elif ch == 2:
if stack:
print("Popped:", stack.pop())
print("Stack:", stack)
else:
print("Stack is empty")
elif ch == 3:
break
14. Write a Python program to implement a queue using a list with enqueue and dequeue
operations.
Answer:
python
# Program to implement queue using list
queue = []
while True:
print("\n1. Enqueue\n2. Dequeue\n3. Exit")
ch = int(input("Enter choice: "))
if ch == 1:
item = input("Enter item to enqueue: ")
queue.append(item)
print("Queue:", queue)
elif ch == 2:
if queue:
print("Dequeued:", queue.pop(0))
print("Queue:", queue)
else:
print("Queue is empty")
elif ch == 3:
break
15. Write a Python program to nd the second largest number in a list without using built-in
functions.
Answer:
python
# Program to find second largest without built-in functions
lst = list(map(int, input("Enter list elements: ").split()))
if len(lst) < 2:
print("Not enough elements")
else:
largest = second = float('-inf')
for num in lst:
if num > largest:
second = largest
largest = num
elif num > second and num != largest:
fi
second = num
print("Second largest:", second)
16. Write a Python program to count the number of vowels in a list of strings.
Answer:
python
# Program to count vowels in a list of strings
lst = input("Enter list of strings (separated by commas):
").split(',')
vowels = 'aeiouAEIOU'
count = 0
for s in lst:
for ch in s:
if ch in vowels:
count += 1
print("Total vowels:", count)
17. Write a Python program to print all unique elements of a list using set comprehension.
Answer:
python
# Program to print unique elements using set comprehension
lst = input("Enter list elements: ").split()
unique = {item for item in lst}
print("Unique elements:", unique)
18. Write a Python program to sort a dictionary by value in ascending order.
Answer:
python
# Program to sort dictionary by value in ascending order
d = eval(input("Enter dictionary (e.g., {'a':3, 'b':1,
'c':2}): "))
sorted_d = dict(sorted(d.items(), key=lambda item: item[1]))
print("Sorted dictionary:", sorted_d)
19. Write a Python program to nd the sum of all elements in a tuple.
Answer:
python
# Program to find sum of all elements in a tuple
tup = tuple(map(int, input("Enter tuple elements:
").split()))
print("Sum of elements:", sum(tup))
20. Write a Python program to implement a simple calculator using a dictionary of functions.
Answer:
fi
python
# Program to implement a simple calculator using dictionary
of functions
def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b
python
# Program to define Student class and display objects
class Student:
def __init__(self, name, rollno):
self.name = name
self.rollno = rollno
python
# Program to demonstrate inheritance: Animal and Dog
class Animal:
def speak(self):
pass
fi
class Dog(Animal):
def speak(self):
print("Dog barks")
d = Dog()
d.speak()
3. Write a Python program to handle a division by zero exception using try-except block.
Answer:
python
# Program to handle division by zero exception
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
try:
print("Result:", a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
4. Write a Python program to open a le in write mode, write some content, and close the le.
Answer:
python
# Program to write to a file and close it
with open("sample.txt", "w") as f:
f.write("Hello, this is sample text.")
print("File written successfully")
5. Write a Python program to read the contents of a le and print them line by line.
Answer:
python
# Program to read file contents line by line
with open("sample.txt", "r") as f:
for line in f:
print(line, end="")
6. Write a Python program to de ne a user-de ned exception for negative age and raise it if
age is negative.
Answer:
python
# Program to define and raise user-defined exception for
negative age
class NegativeAgeError(Exception):
pass
python
# Program to demonstrate operator overloading for addition
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})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print("Sum of vectors:", v3)
8. Write a Python program to copy the contents of one le to another le.
Answer:
python
# Program to copy contents of one file to another
with open("source.txt", "r") as src, open("dest.txt", "w") as
dst:
dst.write(src.read())
print("File copied successfully")
9. Write a Python program to append data to an existing le.
Answer:
python
# Program to append data to an existing file
with open("sample.txt", "a") as f:
f.write("\nAppending new line.")
print("Data appended successfully")
10. Write a Python program to demonstrate the use of nally block in exception handling.
Answer:
python
fi
fi
fi
fi
# Program to demonstrate finally block
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result:", a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This block always executes")
11. Write a Python program to demonstrate containership: de ne a class Library with a list of
Book objects.
Answer:
python
# Program to demonstrate containership: Library with Book
objects
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def display_books(self):
for book in self.books:
print(book.title, "by", book.author)
lib = Library()
b1 = Book("Python Basics", "A. Smith")
b2 = Book("OOP in Python", "B. Lee")
lib.add_book(b1)
lib.add_book(b2)
lib.display_books()
12. Write a Python program to handle multiple exceptions (ValueError and TypeError) in a
single try-except block.
Answer:
python
# Program to handle multiple exceptions
try:
a = int(input("Enter number: "))
b = input("Enter string: ")
fi
print(a + b)
except (ValueError, TypeError):
print("Invalid operation or input")
13. Write a Python program to demonstrate the use of else block with exception handling.
Answer:
python
# Program to demonstrate else block with exception handling
try:
a = int(input("Enter number: "))
b = int(input("Enter another number: "))
print("Sum:", a + b)
except ValueError:
print("Invalid input")
else:
print("No exceptions occurred")
14. Write a Python program to create a le and write user input to it until the user enters
'quit'.
Answer:
python
# Program to write user input to file until 'quit'
with open("user_input.txt", "w") as f:
while True:
line = input("Enter line (type 'quit' to exit): ")
if line == "quit":
break
f.write(line + "\n")
print("File saved")
15. Write a Python program to demonstrate reading and writing binary les.
Answer:
python
# Program to demonstrate reading and writing binary files
with open("data.bin", "wb") as f:
f.write(b"This is binary data.")
with open("data.bin", "rb") as f:
print("Binary file contents:", f.read())
16. Write a Python program to demonstrate the use of with statement for le handling.
Answer:
python
# Program to demonstrate use of with statement for file
handling
fi
fi
fi
with open("sample.txt", "r") as f:
print("File contents:", f.read())
17. Write a Python program to demonstrate private members in a class.
Answer:
python
# Program to demonstrate private members in a class
class MyClass:
def __init__(self, public, private):
self.public = public
self.__private = private
def display(self):
print("Public:", self.public)
print("Private:", self.__private)
python
# Program to count lines, words, and characters in a file
with open("sample.txt", "r") as f:
lines = 0
words = 0
chars = 0
for line in f:
lines += 1
words += len(line.split())
chars += len(line)
print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)
19. Write a Python program to rename a le using the os module.
Answer:
python
# Program to rename a file using os module
import os
os.rename("old.txt", "new.txt")
print("File renamed")
20. Write a Python program to delete a le using the os module.
Answer:
fi
fi
fi
python
# Program to delete a file using os module
import os
os.remove("sample.txt")
print("File deleted")
python
# Function to calculate factorial using recursion
def factorial(n):
if n == 1 or n == 0:
return 1
else:
return n * factorial(n-1)
python
# Function to check if a number is prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
python
# Function to reverse a list
def reverse_list(lst):
return lst[::-1]
python
# Function to count vowels and consonants
def count_vowels_consonants(s):
vowels = "aeiouAEIOU"
v = c = 0
for ch in s:
if ch.isalpha():
if ch in vowels:
v += 1
else:
c += 1
return v, c
python
# Function to find max and min in a list
def find_max_min(lst):
return max(lst), min(lst)
fi
lst = list(map(int, input("Enter numbers (space-separated):
").split()))
mx, mn = find_max_min(lst)
print(f"Maximum: {mx}, Minimum: {mn}")
6. Write a Python function to compute the sum of elements in a list using recursion.
Answer:
python
# Function to compute sum of list using recursion
def sum_list(lst):
if not lst:
return 0
else:
return lst[0] + sum_list(lst[1:])
python
# Function to generate Fibonacci series
def fibonacci(n):
a, b = 0, 1
series = []
for _ in range(n):
series.append(a)
a, b = b, a + b
return series
python
# Function to filter even numbers from a list
def filter_even(lst):
return [x for x in lst if x % 2 == 0]
lst = list(map(int, input("Enter numbers (space-separated):
").split()))
print("Even numbers:", filter_even(lst))
9. Write a Python function using map() to square each element of a list. Use the function for a
user-input list.
Answer:
python
# Function to square each element using map
def square_list(lst):
return list(map(lambda x: x**2, lst))
python
# Function to filter strings longer than given length
def filter_long_strings(lst, length):
return list(filter(lambda s: len(s) > length, lst))
python
# Function to find product using reduce
from functools import reduce
def product_list(lst):
return reduce(lambda x, y: x * y, lst)
python
# Function to sort list of tuples by second element
def sort_by_second(tup_list):
return sorted(tup_list, key=lambda x: x[1])
python
# Function to sum variable number of arguments
def sum_args(*args):
return sum(args)
python
# Lambda function to return square of a number
square = lambda x: x**2
python
# (math_ops.py)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
# (main.py)
import math_ops
python
# (utils/string_ops.py)
def count_vowels(s):
vowels = "aeiouAEIOU"
return sum(1 for ch in s if ch in vowels)
def reverse_string(s):
return s[::-1]
# (main.py)
from utils.string_ops import count_vowels, reverse_string
def demo_vars():
local_var = 5
print("Inside function - local_var:", local_var)
print("Inside function - global_var:", global_var)
demo_vars()
print("Outside function - global_var:", global_var)
# print("Outside function - local_var:", local_var) # This
would raise an error
19. Write a Python function to demonstrate the use of the main module and explain the use of
if __name__ == "__main__":.
Answer:
python
# Function to demonstrate main module usage
def multiply(a, b):
return a * b
if __name__ == "__main__":
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Product:", multiply(a, b))
Explanation:
The if __name__ == "__main__": block ensures that the code inside it executes only
when the script is run directly, not when imported as a module.
20. Write a Python function to create a recursive function that returns the nth term of the
Fibonacci sequence. Call the function for a user input value and print the result.
Answer:
python
# Recursive function to find nth Fibonacci term
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
——————————————————————————————————————-
y = "10"
print(x + int(y))
Answer: 15
Dry Run: x = 5 (integer). y = "10" (string). int(y) converts "10" to integer 10. Then,
x + int(y) = 5 + 10 = 15. The print() function outputs 15.
Question: Predict the output of the following code:
print(3 ** 2 * 4)
Answer: 36
Dry Run: Operator precedence: ** (exponentiation) rst, then *. So, 3 ** 2 = 9, then 9 *
4 = 36. Output is 36.
Question: Predict the output of the following code:
s = "Python"
print(s[1:4])
Answer: yth
Dry Run: s = "Python". Slicing [1:4] extracts characters from index 1 to 3 (4 excluded):
y (1), t (2), h (3). Output is yth.
Question: Predict the output of the following code:
a = 10
b = 3
print(a // b, a % b)
Answer: 3 1
Dry Run: a = 10, b = 3. a // b performs oor division: 10 / 3 = 3.33, oor gives
3. a % b gives remainder: 10 % 3 = 1. Output is 3 1.
Question: Predict the output of the following code:
x = "Hello"
print(x * 2)
Answer: HelloHello
Dry Run: x = "Hello". String repetition x * 2 concatenates Hello twice:
HelloHello. Output is HelloHello.
Question: Predict the output of the following code:
print(float("5.5") + 2)
Answer: 7.5
Dry Run: float("5.5") converts string "5.5" to oat 5.5. Then, 5.5 + 2 = 7.5.
Output is 7.5.
Question: Predict the output of the following code:
s = " Python "
print(s.strip())
Answer: Python
Dry Run: s = " Python ". strip() removes leading and trailing spaces, leaving
Python. Output is Python.
Question: Predict the output of the following code:
x = 7
print(x, type(x))
x = str(x)
print(x, type(x))
fl
fi
fl
fl
Answer: 7 <class 'int'>
7 <class 'str'>
Dry Run: x = 7 (integer). First print: 7, type(7) outputs 7 <class 'int'>. x =
str(x) converts 7 to "7". Second print: "7", type("7") outputs 7 <class
'str'>.
Question: Predict the output of the following code:
print("Python"[::-1])
Answer: nohtyP
Dry Run: "Python"[::-1] uses slicing with step -1, reversing the string: P-y-t-h-o-n
becomes n-o-h-t-y-P. Output is nohtyP.
Question: Predict the output of the following code:
name = "Alice"
print(f"Hi, {name}!")
print(int(x) * 2)
Answer: 246
Dry Run: input("Enter: ") takes "123". int(x) converts "123" to 123. Then,
123 * 2 = 246. Output is 246.
Question: Predict the output of the following code:
s = "Hello,World"
print(s.split(","))
Answer: True
Dry Run: String comparison uses lexicographical order (ASCII). abc (a=97) is less than def
(d=100). Thus, "abc" < "def" is True.
Question: Predict the output of the following code:
x = 3.14
print(int(x))
Answer: 3
Dry Run: x = 3.14 ( oat). int(x) truncates to 3. Output is 3.
Question: Predict the output of the following code:
s = "Python"
print(s.upper().lower())
Answer: python
Dry Run: s = "Python". s.upper() gives PYTHON. Then, PYTHON.lower() gives
python. Output is python.
Question: Predict the output of the following code:
print(len("Hello" + "World"))
Answer: 10
Dry Run: "Hello" + "World" concatenates to "HelloWorld".
len("HelloWorld") counts 10 characters. Output is 10.
Question: Predict the output of the following code:
import math
print(math.ceil(4.2))
Answer: 5
Dry Run: math.ceil(4.2) rounds up to the next integer, 5. Output is 5.
Question: Predict the output of the following code:
s = "abc"
print(s[1] + s[-1])
Answer: bc
Dry Run: s = "abc". s[1] is b. s[-1] is c. Concatenation b + c gives bc. Output is
bc.
Question: Predict the output of the following code:
print("Hello".startswith("He"))
Answer: True
Dry Run: "Hello".startswith("He") checks if Hello begins with He, which is true.
Output is True.
Question: Predict the output of the following code:
x = 5
y = "5"
print(x == int(y), x is int(y))
Answer: Yes
Dry Run: x = 5. Condition: x > 3 (True) and x < 7 (True), so True and True =
True. print("Yes") executes. Output is Yes.
Question: Predict the output of the following code:
for i in range(3):
Answer: 0 1 2
Dry Run: range(3) gives 0, 1, 2. for loop prints each i with end=" ", so numbers are
space-separated. Output is 0 1 2.
Question: Predict the output of the following code:
x = [1, 2, 3]
x.append(4)
print(x)
Answer: [1, 2, 3, 4]
Dry Run: x = [1, 2, 3]. x.append(4) adds 4 to the list, making it [1, 2, 3, 4].
Output is [1, 2, 3, 4].
Question: Predict the output of the following code:
i = 0
while i < 3:
print(i)
i += 1
Answer: 0
1
2
Dry Run: i = 0. While i < 3: print 0, i = 1; print 1, i = 2; print 2, i = 3. Loop
stops. Output is 0, 1, 2 (each on a new line).
Question: Predict the output of the following code:
lst = [1, 2, 3]
print(lst[1:3])
Answer: [2, 3]
Dry Run: lst = [1, 2, 3]. Slicing [1:3] extracts indices 1 to 2: [2, 3]. Output is
[2, 3].
Question: Predict the output of the following code:
s = {1, 2, 2, 3}
print(len(s))
Answer: 3
Dry Run: s = {1, 2, 2, 3} creates a set, removing duplicates: {1, 2, 3}. len(s)
returns 3. Output is 3.
Question: Predict the output of the following code:
for i in [1, 2, 3]:
if i == 2:
break
print(i)
Answer: 1
Dry Run: Loop over [1, 2, 3]. For i = 1, print 1. For i = 2, break stops the loop.
Output is 1.
Question: Predict the output of the following code:
d = {"a": 1, "b": 2}
print(d["b"])
Answer: 2
Dry Run: d = {"a": 1, "b": 2}. d["b"] accesses the value for key "b", which is 2.
Output is 2.
Question: Predict the output of the following code:
lst = [x * 2 for x in range(3)]
print(lst)
Answer: [0, 2, 4]
Dry Run: List comprehension [x * 2 for x in range(3)]: range(3) gives 0,
1, 2. Each x * 2: 0*2=0, 1*2=2, 2*2=4. Output is [0, 2, 4].
Question: Predict the output of the following code:
t = (1, 2, 3)
print(t[0] + t[2])
Answer: 4
Dry Run: t = (1, 2, 3). t[0] = 1, t[2] = 3. 1 + 3 = 4. Output is 4.
Question: Predict the output of the following code:
x = 5
print("Even" if x % 2 == 0 else "Odd")
Answer: Odd
Dry Run: x = 5. x % 2 = 1, so x % 2 == 0 is False. Conditional expression gives
"Odd". Output is Odd.
Question: Predict the output of the following code:
s = {1, 2}
s.add(3)
print(s)
Answer: {1, 2, 3}
Dry Run: s = {1, 2}. s.add(3) adds 3, making {1, 2, 3} (order may vary). Output
is {1, 2, 3}.
Question: Predict the output of the following code:
for i in range(5):
if i % 2 == 0:
print(i, end=",")
Answer: 0,2,4,
Dry Run: range(5): 0, 1, 2, 3, 4. For even i (0, 2, 4), print with end=",": 0,,
2,, 4,. Output is 0,2,4,.
Question: Predict the output of the following code:
d = {"x": 10, "y": 20}
for k in d:
print(k, end=" ")
Answer: x y
Dry Run: d = {"x": 10, "y": 20}. Loop iterates over keys: "x", "y". print(k,
end=" ") outputs x y. Output is x y.
Question: Predict the output of the following code:
lst = [1, 2, 3]
lst.pop(1)
print(lst)
Answer: [1, 3]
Dry Run: lst = [1, 2, 3]. lst.pop(1) removes element at index 1 (2), leaving [1,
3]. Output is [1, 3].
Question: Predict the output of the following code:
t = (1, 2, 2, 3)
print(t.count(2))
Answer: 2
Dry Run: t = (1, 2, 2, 3). t.count(2) counts occurrences of 2, which is 2. Output
is 2.
Question: Predict the output of the following code:
s1 = {1, 2}
s2 = {2, 3}
print(s1 | s2)
Answer: {1, 2, 3}
Dry Run: s1 = {1, 2}, s2 = {2, 3}. s1 | s2 computes union, combining all unique
elements: {1, 2, 3}. Output is {1, 2, 3}.
Question: Predict the output of the following code:
x = [1, 2, 3]
print(2 in x)
Answer: True
Dry Run: x = [1, 2, 3]. 2 in x checks if 2 is in the list, which is True. Output is
True.
Question: Predict the output of the following code:
d = {x: x*2 for x in range(2)}
print(d)
Answer: {0: 0, 1: 2}
Dry Run: Dictionary comprehension {x: x*2 for x in range(2)}: range(2) gives
0, 1. For x=0, 0:0*2=0; for x=1, 1:1*2=2. Output is {0: 0, 1: 2}.
Question: Predict the output of the following code:
for i in range(3):
if i == 1:
continue
print(i)
Answer: 0
2
Dry Run: range(3): 0, 1, 2. For i=0, print 0. For i=1, continue skips printing. For
i=2, print 2. Output is 0, 2 (each on a new line).
return a + b
print(add(3))
Answer: 5
Dry Run:
add(a, b=2) de nes a function with a default parameter b=2.
add(3) calls add with a=3, using default b=2.
Inside add, 3 + 2 = 5.
Output is 5.
Question: Predict the output of the following code:
def greet(name):
return sum(args)
print(sum_nums(1, 2, 3))
Answer: 6
Dry Run:
sum_nums(*args) accepts variable arguments as a tuple.
sum_nums(1, 2, 3) passes 1, 2, 3, so args = (1, 2, 3).
sum(args) calculates 1 + 2 + 3 = 6.
Output is 6.
Question: Predict the output of the following code:
def info(**kwargs):
return kwargs
print(info(x=1, y=2))
if n == 0:
return 1
return n * fact(n-1)
print(fact(3))
Answer: 6
Dry Run:
fact(3): n=3, not 0, so 3 * fact(2).
fact(2): 2 * fact(1).
fact(1): 1 * fact(0).
fact(0): 1.
Then: 1 * 1 = 1, 2 * 1 = 2, 3 * 2 = 6.
Output is 6.
Question: Predict the output of the following code:
double = lambda x: x * 2
print(double(4))
Answer: 8
Dry Run:
double = lambda x: x * 2 de nes an anonymous function.
double(4) computes 4 * 2 = 8.
Output is 8.
Question: Predict the output of the following code:
nums = [1, 2, 3]
Answer: [1, 4, 9]
Dry Run:
map(lambda x: x**2, nums) applies x**2 to each element in [1, 2, 3].
For 1: 1**2 = 1, 2: 2**2 = 4, 3: 3**2 = 9.
list(map(...)) returns [1, 4, 9].
Output is [1, 4, 9].
Question: Predict the output of the following code:
nums = [1, 2, 3, 4]
print(list(filter(lambda x: x % 2 == 0, nums)))
Answer: [2, 4]
Dry Run:
filter(lambda x: x % 2 == 0, nums) keeps elements where x % 2 ==
0 is True.
For [1, 2, 3, 4]: 1 % 2 = 1 (False), 2 % 2 = 0 (True), 3 % 2 = 1
(False), 4 % 2 = 0 (True).
fi
list(filter(...)) returns [2, 4].
Output is [2, 4].
Question: Predict the output of the following code:
from functools import reduce
Answer: 6
Dry Run:
reduce(lambda x, y: x + y, [1, 2, 3]) applies x + y cumulatively.
Step 1: 1 + 2 = 3.
Step 2: 3 + 3 = 6.
Output is 6.
Question: Predict the output of the following code:
nums = [1, 2]
print(add(*nums))
def add(a, b):
return a + b
Answer: 3
Dry Run:
nums = [1, 2].
add(*nums) unpacks nums as add(1, 2).
add(1, 2) returns 1 + 2 = 3.
Output is 3.
Question: Predict the output of the following code:
import math
print(math.floor(3.7))
Answer: 3
Dry Run:
math.floor(3.7) rounds down to the nearest integer.
3.7 becomes 3.
Output is 3.
Question: Predict the output of the following code:
if __name__ == "__main__":
print("Main")
Answer: Main
Dry Run:
__name__ == "__main__" is True when the script runs directly.
print("Main") executes.
Output is Main.
Question: Predict the output of the following code:
import random
random.seed(1)
print(random.randint(1, 3))
Answer: 2
Dry Run:
random.seed(1) sets a xed random sequence.
random.randint(1, 3) generates a number between 1 and 3 (inclusive). With seed
1, it consistently returns 2 (implementation-dependent).
Output is 2.
Question: Predict the output of the following code:
def test():
return 1, 2
x, y = test()
print(x, y)
Answer: 1 2
Dry Run:
test() returns a tuple (1, 2).
x, y = test() unpacks (1, 2) into x=1, y=2.
print(x, y) outputs 1 2.
Output is 1 2.
Question: Predict the output of the following code:
import math as m
print(m.pi)
Answer: 3.141592653589793
Dry Run:
import math as m aliases math to m.
m.pi accesses the constant pi.
Output is 3.141592653589793.
Question: Predict the output of the following code:
def outer():
x = 1
def inner():
return x
return inner()
print(outer())
Answer: 1
Dry Run:
outer() de nes x = 1 and calls inner().
inner() accesses x from outer’s scope, returning 1.
outer() returns inner()’s result.
Output is 1.
fi
fi
Question: Predict the output of the following code:
nums = [1, 2, 3]
print(len(list(map(str, nums))))
Answer: 3
Dry Run:
map(str, nums) converts [1, 2, 3] to ["1", "2", "3"].
list(map(...)) creates the list ["1", "2", "3"].
len(...) returns 3.
Output is 3.
Question: Predict the output of the following code:
def calc(x, y=1, *args):
return x + y + sum(args)
print(calc(2, 3, 4))
Answer: 9
Dry Run:
calc(2, 3, 4): x=2, y=3, args=(4,).
sum(args) = 4.
x + y + sum(args) = 2 + 3 + 4 = 9.
Output is 9.
Question: Predict the output of the following code:
import sys
print(len(sys.argv))
Answer: 1
Dry Run:
sys.argv is a list of command-line arguments, starting with the script name.
When run directly, sys.argv = [script_name].
len(sys.argv) is 1.
Output is 1.
Question: Predict the output of the following code:
def double(x):
return lambda y: x * y
f = double(2)
print(f(3))
Answer: 6
Dry Run:
double(2) returns a lambda function lambda y: 2 * y.
f = double(2), so f is lambda y: 2 * y.
f(3) computes 2 * 3 = 6.
Output is 6.
Unit IV: OOP, Exception Handling, and File Handling (2
Marks Each)
Question: Predict the output of the following code:
class Dog:
def bark(self):
return "Woof"
d = Dog()
print(d.bark())
Answer: Woof
Dry Run:
Dog class de nes bark method returning "Woof".
d = Dog() creates an instance.
d.bark() calls the method, returning "Woof".
Output is Woof.
Question: Predict the output of the following code:
class Car:
Answer: Toyota
Dry Run:
Car class’s __init__ sets self.model = model.
c = Car("Toyota") sets c.model = "Toyota".
print(c.model) outputs Toyota.
Output is Toyota.
Question: Predict the output of the following code:
class Animal:
count = 0
def __init__(self):
Animal.count += 1
a1 = Animal()
a2 = Animal()
print(Animal.count)
Answer: 2
Dry Run:
Animal.count is a class variable, initially 0.
a1 = Animal() calls __init__, incrementing count to 1.
a2 = Animal() increments count to 2.
fi
Output is 2.
Question: Predict the output of the following code:
class Vector:
Answer: 5
Dry Run:
v1 = Vector(2), v2 = Vector(3).
v1 + v2 calls __add__, returning a new Vector with x = 2 + 3 = 5.
(v1 + v2).x accesses x, which is 5.
Output is 5.
Question: Predict the output of the following code:
class Animal:
def sound(self):
return "Generic"
class Dog(Animal):
def sound(self):
return "Woof"
d = Dog()
print(d.sound())
Answer: Woof
Dry Run:
Dog inherits from Animal but overrides sound.
d = Dog() creates a Dog instance.
d.sound() calls Dog’s sound, returning Woof.
Output is Woof.
Question: Predict the output of the following code:
class Parent:
def __init__(self):
self.x = 1
class Child(Parent):
def __init__(self):
super().__init__()
self.y = 2
c = Child()
print(c.x, c.y)
Answer: 1 2
Dry Run:
Child’s __init__ calls Parent’s __init__ via super(), setting x=1.
Then sets y=2.
c.x, c.y outputs 1 2.
Output is 1 2.
Question: Predict the output of the following code:
try:
x = 1 / 0
except ZeroDivisionError:
print("Error")
Answer: Error
Dry Run:
1 / 0 raises ZeroDivisionError.
except ZeroDivisionError catches it and prints "Error".
Output is Error.
Question: Predict the output of the following code:
try:
x = int("abc")
except ValueError:
print("Invalid")
Answer: Invalid
Dry Run:
int("abc") raises ValueError (invalid integer).
except ValueError catches it and prints "Invalid".
Output is Invalid.
Question: Predict the output of the following code:
try:
x = 5
except:
print("Error")
else:
print("No Error")
Answer: No Error
Dry Run:
try: x = 5 executes without errors.
except is skipped.
else block prints "No Error".
Output is No Error.
Question: Predict the output of the following code:
try:
x = 1 / 0
except:
print("Error")
finally:
print("Done")
Answer: Error
Done
Dry Run:
1 / 0 raises ZeroDivisionError.
except prints "Error".
finally always runs, printing "Done".
Output is Error and Done (new lines).
Question: Predict the output of the following code:
class MyError(Exception):
pass
try:
raise MyError("Custom")
except MyError:
print("Caught")
Answer: Caught
Dry Run:
MyError is a custom exception.
raise MyError("Custom") raises it.
except MyError catches it and prints "Caught".
Output is Caught.
Question: Predict the output of the following code:
with open("test.txt", "w") as f:
f.write("Hi")
print("Done")
Answer: Done
Dry Run:
with open("test.txt", "w") as f opens test.txt in write mode.
f.write("Hi") writes "Hi".
with closes the le.
print("Done") outputs Done.
Question: Predict the output of the following code:
class Box:
Answer: Toy
Dry Run:
Box’s __init__ sets self.item = item.
b = Box("Toy") sets b.item = "Toy".
print(b.item) outputs Toy.
Output is Toy.
Question: Predict the output of the following code:
try:
lst = [1, 2]
print(lst[2])
except IndexError:
print("Out of range")
x = 1
class B(A):
pass
print(B.x)
Answer: 1
Dry Run:
A has class variable x = 1.
B inherits from A, so B.x accesses A’s x.
Output is 1.
Question: Predict the output of the following code:
with open("test.txt", "w") as f:
f.write("Hello\nWorld")
with open("test.txt", "r") as f:
print(f.readline())
Answer: Hello
Dry Run:
First with writes "Hello\nWorld" to test.txt.
Second with reads the rst line with readline(), which is "Hello\n".
print outputs Hello (newline removed).
Output is Hello.
Question: Predict the output of the following code:
class Point:
Answer: 5
Dry Run:
__init__ sets private __x = 5.
get_x() returns __x.
p.get_x() returns 5.
Output is 5.
Question: Predict the output of the following code:
try:
f = open("no_file.txt")
except FileNotFoundError:
print("Not found")
def move(self):
return "Moving"
v = Vehicle()
print(v.move())
Answer: Moving
Dry Run:
Vehicle’s move method returns "Moving".
v = Vehicle() creates an instance.
v.move() calls the method, returning "Moving".
Output is Moving.
Question: Predict the output of the following code:
with open("test.txt", "w") as f:
fi
fi
f.write("ABC")
with open("test.txt", "r") as f:
f.seek(1)
print(f.read())
Answer: BC
Dry Run:
First with writes "ABC" to test.txt.
Second with opens in read mode, seek(1) moves the pointer to index 1.
read() reads from index 1: "BC".
Output is BC.