0% found this document useful (0 votes)
6 views

Question Bank Python BCA PDF

The document is a question bank focused on Python programming, covering topics such as Python basics, data types, control structures, and data structures. It includes very short answer questions that test knowledge on various Python concepts, functions, and syntax. Each question is followed by a concise answer, making it a useful resource for learners and practitioners of Python.

Uploaded by

rsatapathy930
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Question Bank Python BCA PDF

The document is a question bank focused on Python programming, covering topics such as Python basics, data types, control structures, and data structures. It includes very short answer questions that test knowledge on various Python concepts, functions, and syntax. Each question is followed by a concise answer, making it a useful resource for learners and practitioners of Python.

Uploaded by

rsatapathy930
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Python: Question Bank

Part 1: VERY SHORT ANSWER QUESTIONS

Unit I: Python Basics and Strings


1. What is Python? Python is a high-level, interpreted programming language known for its simple
and readable syntax. It was created by Guido van Rossum and is widely used for web development,
data analysis, arti cial intelligence, and automation.

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.

Unit II: Control Structures and Data Structures

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.

17. What is dictionary comprehension? Dictionary comprehension is a concise way to create


dictionaries using a single line of code. It follows the syntax {key: value for item in iterable}. For
example, {x: x**2 for x in range(5)} creates a dictionary where keys are numbers 0-4 and values
are their squares.

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.

16. De ne a package in Python. A package is a collection of related modules organized in a


directory with an init.py le.

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.

Unit IV: OOP, Exception Handling, and File Handling


1. What keyword is used to de ne a class? The class keyword is used to de ne a class in Python.

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.

7. Write the syntax of a try-except block. try: code_that_might_fail except ExceptionType:


code_to_handle_error

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.

11. De ne operator overloading. Operator overloading allows custom classes to de ne behavior


for built-in operators like +, -, *.

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.

16. De ne containership. Containership (composition) is when one class contains objects of


another class as its attributes.

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.

————————————————————————————————————————

————————————————————————————————————————

————————————————————————————————————————

UNIT I – MCQ (1 MARK QUESTIONS)

1. Which of the following is the correct le extension for Python les?


a) .pt
b) .pyt
c) .py
d) .p
Answer: c
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
2. What will be the output of: type("5")?
a) int
b) str
c) oat
d) bool
Answer: b

3. Which of the following is not a valid identi er in Python?


a) _value
b) val_123
c) 123val
d) value
Answer: c

4. Which of the following is used to import a module in Python?


a) include
b) import
c) using
d) package
Answer: b

5. What is the result of 3 ** 2 in Python?


a) 6
b) 9
c) 8
d) 12
Answer: b

6. Which one of the following is an immutable type?


a) list
b) dictionary
c) set
d) string
Answer: d

7. What is the output of: print("abc" + "123")?


a) abc123
b) abc 123
c) abc+123
d) Error
Answer: a

8. Which method is used to convert all characters of a string to lowercase?


a) lower()
b) down()
c) islower()
d) tolower()
Answer: a

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

10. What will be the output of int("10") + float("5.5")?


a) 15.5
b) 105.5
c) 10.5
d) Error
Answer: a

11. Which character is used in Python for comments?


a) //
b) /* */
c) #
d) --
Answer: c

12. Which of the following keywords is used to de ne a function in Python?


a) function
b) def
c) func
d) de ne
Answer: b

13. Which one is a correct container type?


a) integer
b) string
c) dictionary
d) oat
Answer: c

14. The result of type([]) is:


a) <class ‘tuple’>
b) <class ‘list’>
c) <class ‘set’>
d) <class ‘dict’>
Answer: b

15. What is the output of: len("Python")?


a) 6
b) 5
c) 7
d) 8
Answer: a

16. What is returned by str(10.0)?


a) 10
b) 10.0
c) "10.0"
d) Error
Answer: c
fl
fi
fi
17. What is the precedence of * and + in 3 + 4 * 5?
a) + rst then *
b) Left to right
c) * rst then +
d) Both same
Answer: c

18. What is the result of print("abc" * 3)?


a) abcabcabc
b) abc*3
c) abc abc abc
d) Error
Answer: a

19. What is the output of print("5" + str(5))?


a) 10
b) 55
c) Error
d) 5str(5)
Answer: b

20. Which function is used to nd the memory location of an object?


a) mem()
b) id()
c) addr()
d) object()
Answer: b

21. The function ord('A') returns:


a) 64
b) 65
c) A
d) Error
Answer: b

22. Which of the following are valid multi-line delimiters in Python?


a) // //
b) \ \n
c) ''' '''
d) None of these
Answer: c

23. Which function gives Unicode of a character?


a) char()
b) uni()
c) ord()
d) str()
Answer: c

24. What will print("hello".capitalize()) give?


a) Hello
b) hello
fi
fi
fi
c) HELLO
d) hELLO
Answer: a

25. What is the result of print("a" == "A")?


a) True
b) False
c) Error
d) None
Answer: b

26. Which function can be used to get string input from the console?
a) read()
b) input()
c) gets()
d) scan()
Answer: b

27. Which of these is not a Python keyword?


a) def
b) elif
c) lambda
d) void
Answer: d

28. Which of the following will create a string in Python?


a) str = 'Hello'
b) str = "Hello"
c) str = '''Hello'''
d) All of these
Answer: d

29. Which operator is used for exponentiation in Python?


a) ^
b) **
c) %
d) //
Answer: b

30. How do you print without a newline?


a) print("Hello", end="")
b) print("Hello", stop="")
c) print("Hello", noendl="")
d) print("Hello", newline="")
Answer: a
Unit II – MCQs (1 Mark Each)

1. Which of the following is not a valid Python loop?


a) for
b) while
c) do-while
d) None of the above
Answer: c) do-while

2. Which of the following statements is used to exit a loop prematurely?


a) continue
b) stop
c) break
d) exit
Answer: c) break

3. Which keyword is used when no operation is to be performed?


a) continue
b) void
c) pass
d) skip
Answer: c) pass

4. The ‘else’ clause in a loop executes:


a) Only when loop is in nite
b) Only when loop terminates without break
c) Only when loop runs once
d) Always after loop
Answer: b) Only when loop terminates without break

5. Which function returns True if all items in an iterable are true?


a) any()
b) all()
c) each()
d) every()
Answer: b) all()

6. Which data structure in Python is mutable and ordered?


a) Tuple
b) List
c) Set
d) String
Answer: b) List

7. Which data type does not allow duplicate elements?


a) List
b) Tuple
c) Set
d) Dictionary
Answer: c) Set
fi
8. What is the output of len([1, 2, 3])?
a) 2
b) 3
c) Error
d) None
Answer: b) 3

9. Which method adds an element at the end of a list?


a) insert()
b) add()
c) append()
d) extend()
Answer: c) append()

10. What does the pop() method do in a list?


a) Adds item
b) Removes and returns last item
c) Deletes list
d) Copies the list
Answer: b) Removes and returns last item

11. What will set([1, 2, 2, 3]) return?


a) [1, 2, 3]
b) {1, 2, 2, 3}
c) {1, 2, 3}
d) Error
Answer: c) {1, 2, 3}

12. Which operation is not valid on a set?


a) Indexing
b) Union
c) Intersection
d) Difference
Answer: a) Indexing

13. Which of the following is a tuple?


a) [1, 2]
b) {1, 2}
c) (1, 2)
d) <1, 2>
Answer: c) (1, 2)

14. Tuples are:


a) Mutable
b) Immutable
c) Mutable if nested
d) Mutable if not empty
Answer: b) Immutable

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()

17. What will list(range(2, 10, 2)) return?


a) [2, 4, 6, 8, 10]
b) [2, 4, 6, 8]
c) [2, 3, 4, 5]
d) Error
Answer: b) [2, 4, 6, 8]

18. What does any([]) return?


a) True
b) False
c) None
d) Error
Answer: b) False

19. Which of the following is a dictionary comprehension?


a) {k: v for k, v in pairs}
b) [k: v for k, v in pairs]
c) (k: v for k, v in pairs)
d) {k v for k, v in pairs}
Answer: a) {k: v for k, v in pairs}

20. Which is the correct syntax for list comprehension?


a) [x for x in range(5)]
b) (x for x in range(5))
c) {x for x in range(5)}
d) x for x in range(5)
Answer: a) [x for x in range(5)]

21. What will d = {"a":1, "b":2}; d["c"] return?


a) None
b) Error
c) 0
d) 'c'
Answer: b) Error

22. How do you loop through a set in Python?


a) Using indexing
b) Using a for loop
c) Using while loop only
d) You cannot loop
Answer: b) Using a for loop

23. Which of these statements creates an empty dictionary?


a) {}
b) []
c) set()
d) dict()
Answer: d) dict()

24. Which method returns a list of keys in a dictionary?


a) get()
b) keys()
c) items()
d) values()
Answer: b) keys()

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

26. What is the result of 4 and 0 in Python?


a) True
b) False
c) 4
d) 0
Answer: d) 0

27. Which function is used to input a value from the user?


a) read()
b) scanf()
c) input()
d) get()
Answer: c) input()

28. Which of the following is a valid way to declare a list?


a) list = (1,2,3)
b) list = [1,2,3]
c) list = {1,2,3}
d) list = <1,2,3>
Answer: b) list = [1,2,3]

29. Which of the following removes a speci ed key from a dictionary?


a) popitem()
b) pop(key)
c) remove(key)
d) delete(key)
Answer: b) pop(key)
fi
30. Which is a valid set operation in Python?
a) +
b) *
c) -
d) /
Answer: c) -

Unit III – MCQs (1 Mark Each)

1. Which keyword is used to de ne a function in Python?


a) def
b) function
c) fun
d) de ne
Answer: a) def

2. What is the output of type(lambda x: x)?


a) <class 'function'>
b) <class 'lambda'>
c) <class 'method'>
d) Error
Answer: a) <class 'function'>

3. Which built-in function is used to get user input in Python 3?


a) input()
b) raw_input()
c) scanf()
d) gets()
Answer: a) input()

4. Which function returns the memory location (identity) of an object?


a) id()
b) mem()
c) location()
d) reference()
Answer: a) id()

5. What does the map() function return?


a) A list
b) A tuple
c) A map object (iterator)
d) A dictionary
Answer: c) A map object (iterator)

6. What will filter() do in Python?


a) Removes null elements
b) Returns elements where function returns True
c) Filters only odd numbers
d) Filters only even numbers
Answer: b) Returns elements where function returns True
fi
fi
7. Which function is used to combine items cumulatively?
a) reduce()
b) map()
c) lter()
d) accumulate()
Answer: a) reduce()

8. Which module must be imported to use reduce() in Python 3?


a) functools
b) itertools
c) operators
d) collections
Answer: a) functools

9. Which of the following is not a valid function argument type in Python?


a) Required
b) Optional
c) Positional
d) Mandatory
Answer: d) Mandatory

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

11. Which of these can be used to create an anonymous function in Python?


a) lambda
b) def
c) unnamed
d) None of the above
Answer: a) lambda

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):

13. What will print("main" == __name__) return when run directly?


a) True
b) False
c) Error
d) None
Answer: b) False

14. Which module is executed rst when a Python le runs?


a) main
b) main()
fi
fi
fi
fi
c) start.py
d) rst()
Answer: a) main

15. Which keyword is used to import a module in Python?


a) using
b) import
c) include
d) module
Answer: b) import

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

17. What is __init__.py used for?


a) Initializes Python
b) Makes a directory a package
c) Imports built-in modules
d) Contains class de nitions
Answer: b) Makes a directory a package

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":

19. What does the dir() function return?


a) Directory path
b) Attributes and methods of an object/module
c) File list
d) Object type
Answer: b) Attributes and methods of an object/module

20. What is *args used for in function de nitions?


a) Keyword arguments
b) Variable number of non-keyword arguments
c) Global arguments
d) Unpacking dictionaries
Answer: b) Variable number of non-keyword arguments

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):

23. Which method is automatically called when a module is imported?


a) init()
b) main()
c) name()
d) None
Answer: a) init()

24. What does globals() return?


a) Current global symbol table as dictionary
b) Local variable list
c) File paths
d) Imported modules
Answer: a) Current global symbol table as dictionary

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

26. Which operator is used for argument unpacking?


a) *
b) **
c) &&
d) #
**Answer: a) *

27. Which operator is used for keyword argument unpacking?


a) *
b) **
c) &&
d) %%
**Answer: b) **

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

29. Which one of the following is true about Python modules?


a) They cannot contain variables
b) They must contain a class
fi
c) They can include functions, variables, classes
d) They can’t be imported
Answer: c) They can include functions, variables, classes

30. What is the le extension of a Python module?


a) .pm
b) .pyc
c) .pym
d) .py
Answer: d) .py

Unit IV – MCQs (1 Mark Each)

1. Which of the following is used to de ne a class in Python?


a) class
b) def
c) object
d) de ne
Answer: a) class

2. Which function is automatically called when an object is created?


a) new()
b) init()
c) class()
d) object()
Answer: b) init()

3. Which of the following is true about private members in Python?


a) They start with @
b) They start with a single underscore _
c) They start with double underscore __
d) They use the keyword private
Answer: c) They start with double underscore __

4. Which of the following is not a type of inheritance in Python?


a) Single
b) Multiple
c) Hierarchical
d) Procedural
Answer: d) Procedural

5. Which keyword is used for inheritance in Python?


a) inherits
b) extends
c) implements
d) class with subclass
Answer: d) class with subclass

6. Which method is used to represent objects as strings?


a) init()
b) str()
fi
fi
fi
c) repr()
d) show()
Answer: b) str()

7. Which keyword is used to raise an exception?


a) throw
b) raise
c) except
d) error
Answer: b) raise

8. What is the output of type(open)?


a) function
b) le
c) builtin_function_or_method
d) open le
Answer: c) builtin_function_or_method

9. Which block is always executed, regardless of exceptions?


a) nally
b) except
c) else
d) try
Answer: a) nally

10. Which of the following statements is used to handle exceptions?


a) raise
b) catch
c) except
d) error
Answer: c) except

11. Which of the following is used to handle le closing safely in Python?


a) close()
b) with
c) shutdown()
d) le.close()
Answer: b) with

12. Which of the following opens a le for writing only?


a) 'r'
b) 'rw'
c) 'w'
d) 'a+'
Answer: c) 'w'

13. Which function is used to read a single line from a le?


a) read()
b) readline()
c) readlines()
d) input()
Answer: b) readline()
fi
fi
fi
fi
fi
fi
fi
fi
14. Which le mode opens the le for both reading and writing?
a) r+
b) w
c) a
d) x
Answer: a) r+

15. Which of the following keywords is used to de ne a method inside a class?


a) function
b) def
c) method
d) de ne
Answer: b) def

16. Which operator can be overloaded using __add__() method?


a) +
b) -
c) *
d) All of the above
Answer: d) All of the above

17. What will object.__str__() return if not overridden?


a) Class name
b) String of object
c) Memory address of object
d) Object attributes
Answer: c) Memory address of object

18. Which keyword is used to check for exceptions?


a) try
b) test
c) scan
d) debug
Answer: a) try

19. Which of the following is an example of a user-de ned exception?


a) ZeroDivisionError
b) ValueError
c) MyError
d) FileNotFoundError
Answer: c) MyError

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'

21. What does file.read() return if the le is empty?


a) Error
b) None
fi
fi
fi
fi
fi
fi
fi
c) Blank string
d) Null
Answer: c) Blank string

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

23. Which method is called when an object is deleted?


a) del()
b) destroy()
c) end()
d) exit()
Answer: a) del()

24. Which keyword is used to inherit from a parent class?


a) inherit
b) super
c) class Child(Parent)
d) subclass
Answer: c) class Child(Parent)

25. What will file.seek(0) do?


a) Move pointer to end
b) Move pointer to beginning
c) Deletes content
d) Closes the le
Answer: b) Move pointer to beginning

26. Which of the following methods reads entire le content at once?


a) readline()
b) read()
c) readlines()
d) le.readone()
Answer: b) read()

27. Which function is used to check if a method is callable?


a) callable()
b) method()
c) check()
d) function()
Answer: a) callable()

28. What does super() do in a derived class?


a) Calls parent methods
b) Creates a superclass
c) Deletes base class
d) Overrides base class
Answer: a) Calls parent methods
fi
fi
fi
fi
fi
29. Which of the following is true about with statement for le handling?
a) Automatically closes le
b) Makes le read-only
c) Encrypts le
d) Opens le in append mode
Answer: a) Automatically closes le

30. Which exception is raised when dividing by zero?


a) ValueError
b) ZeroDivisionError
c) ArithmeticError
d) DivideByZero
Answer: b) ZeroDivisionError

————————————————————————————————————————

————————————————3. Short ANSWERS————————————————

————————————————————————————————————————

Unit I: Python Basics and Strings – Short Answer Questions (2


Marks)

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`.

2. Differentiate between mutable and immutable data types in


Python with examples.
- *Answer:* Mutable types can be modified after creation (e.g.,
lists, dictionaries). Immutable types cannot be changed (e.g.,
strings, tuples).

3. Explain operator precedence in Python with an example.


- *Answer:* Operator precedence defines the order of
operations. Example: In `3 + 4 * 2`, multiplication (`*`) is
evaluated first, yielding `11`.

4. What is type conversion? Give an example of implicit and


explicit conversion.
- *Answer:* Converting one data type to another. Implicit: `5 +
2.0` → `7.0` (int to float). Explicit: `int("10")` → `10`.

5. List any four built-in functions in Python and their uses.


- *Answer:* `len()` (length), `type()` (data type), `input()`
(user input), `print()` (output).

6. What is the purpose of indentation in Python?


fi
fi
fi
fi
fi
fi
- *Answer:* Indentation defines code blocks (like loops,
functions) instead of using braces.

7. How do you write a multi-line statement in Python?


- *Answer:* Use a backslash (`\`) at the end of a line or
parentheses for implicit line continuation.

8. What are Python comments? How are single-line and multi-line


comments written?
- *Answer:* Comments explain code. Single-line: `# comment`.
Multi-line: `'''comment'''` or `"""comment"""`.

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'`.

10. Why are strings immutable in Python?


- *Answer:* Once created, strings cannot be modified. Any
operation creates a new string.

11. Name four string methods and their uses.


- *Answer:*
- `upper()` → Converts to uppercase.
- `split()` → Splits into a list.
- `strip()` → Removes whitespace.
- `replace()` → Replaces substrings.

12. How does string comparison work in Python?


- *Answer:* Lexicographical (dictionary) order based on
Unicode values.

13. What is formatted printing in Python? Give an example.


- *Answer:* Using `f-strings` or `format()` for dynamic
output. Example: `f"Value: {x}"`.

14. What is the difference between `input()` and `raw_input()` in


Python?
- *Answer:* In Python 3, `input()` reads a string.
`raw_input()` was in Python 2 (removed in Python 3).

15. How do you convert a string to lowercase in Python?


- *Answer:* Using the `lower()` method. Example:
`"HELLO".lower()` → `"hello"`.

16. What is the difference between `is` and `==` in Python?


Provide an example.
- *Answer:* `==` checks value equality, while `is` checks
identity (memory location).
```python
a = [1, 2]
b = [1, 2]
print(a == b) # True (same values)
print(a is b) # False (different objects)
```

17. Explain the use of `//`, `%`, and `` operators with examples.
- *Answer:*
- `//` (Floor division): `7 // 2` → `3`
- `%` (Modulus): `7 % 2` → `1`
- `` (Exponentiation): `2 3` → `8`

18. What are the rules for naming identifiers in Python?


- *Answer:*
- Cannot start with a digit.
- No special symbols except `_`.
- Case-sensitive.
- Cannot be a keyword.

19. How does Python handle integer overflow?


- *Answer:* Python integers have unlimited precision, so no
overflow occurs.

20. What is the purpose of the `type()` function? Give an example.


- *Answer:* Returns the data type of an object. Example:
`type(5.0)` → `<class 'float'>`.

21. Write a Python statement to swap two variables without a


temporary variable.
- *Answer:*
```python
a, b = 5, 10
a, b = b, a # Swapping
```

22. What is the difference between `math.floor()` and `int()` for


negative numbers?
- *Answer:*
- `math.floor(-3.7)` → `-4` (rounds down)
- `int(-3.7)` → `-3` (truncates decimal)

23. How do you force a floating-point division in Python?


- *Answer:* Use at least one float operand. Example: `5 / 2.0`
→ `2.5`.

24. What is the output of `print(0.1 + 0.2 == 0.3)`? Explain.


- *Answer:* `False` due to floating-point precision errors.
Use `math.isclose()` for comparisons.

25. What is the purpose of the `help()` function?


- *Answer:* Displays documentation for Python objects.
Example: `help(str.upper)`.

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
```

27. What is string interpolation? Show with an example.


- *Answer:* Embedding variables in strings. Example:
```python
name = "Alice"
print(f"Hello, {name}!") # f-string (Python 3.6+)
```

28. How do you check if a string contains only digits?


- *Answer:* Use `str.isdigit()`. Example: `"123".isdigit()` →
`True`.

29. What is the difference between `str.strip()` and


`str.split()`?
- *Answer:*
- `strip()` removes leading/trailing whitespace.
- `split()` divides a string into a list based on a
delimiter.

30. Write a Python code snippet to count vowels in a string.


- *Answer:*
```python
s = "Python"
vowels = sum(1 for char in s.lower() if char in 'aeiou')
print(vowels) # Output: 1 ('o')
```

### 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)`.

17. Explain the `pass` statement in Python.


- *Answer:* A null operation used as a placeholder in empty
code blocks.

18. Differentiate between `break` and `continue` in loops.


- *Answer:* `break` exits the loop; `continue` skips the
current iteration.

19. What is the purpose of the `else` block in a loop?


- *Answer:* Executes when the loop completes normally (without
`break`).

20. Write a Python `for` loop to print numbers from 1 to 5.


- *Answer:*
```python
for i in range(1, 6):
print(i)
```

Data Structures
21. How do you create a list in Python? Give an example.
- *Answer:* Using square brackets. Example: `my_list = [1, 2,
3]`.

22. What is list slicing? Demonstrate with an example.


- *Answer:* Extracting a portion of a list. Example:
`nums[1:3]` gives elements at index 1 and 2.

23. How are tuples different from lists?


- *Answer:* Tuples are immutable, while lists are mutable.

24. What is a set in Python? How is it created?


- *Answer:* Unordered collection of unique elements. Example:
`my_set = {1, 2, 3}`.

25. Explain dictionary comprehension with an example.


- *Answer:* Creates dictionaries concisely. Example: `{x: x2
for x in range(3)}` → `{0: 0, 1: 1, 2: 4}`.

26. How do you access values from a dictionary?


- *Answer:* Using keys. Example: `dict["key"]` or
`dict.get("key")`.

27. What are the advantages of using list comprehension?


- *Answer:* Concise syntax, faster execution, and readability.

28. Write a Python code snippet to merge two dictionaries.


- *Answer:*
```python
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = {dict1, dict2}
```

29. How do you check if a key exists in a dictionary?


- *Answer:* Using `in` keyword. Example: `"key" in my_dict`.

30. What is the use of the `zip()` function in Python?


- *Answer:* Combines multiple iterables into tuples. Example:
`zip([1, 2], ['a', 'b'])`.
16. What is short-circuit evaluation in logical operators?
- *Answer:* Stops evaluation if the result is already
determined. Example:
```python
False and (5 > 3) # Stops at False
True or (10 < 5) # Stops at True
```

17. Write a Python `while` loop to print even numbers between 1


and 10.
- *Answer:*
```python
i = 2
while i <= 10:
print(i)
i += 2
```

18. What is the purpose of the `enumerate()` function? Give an


example.
- *Answer:* Adds a counter to an iterable. Example:
```python
for idx, val in enumerate(["a", "b"]):
print(idx, val) # Output: 0 a, 1 b
```

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]`

20. What is an infinite loop? How can you avoid it?


- *Answer:* A loop that never terminates. Avoid by ensuring a
valid exit condition.

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]
```

22. What is the difference between `list.pop()` and


`list.remove()`?
- *Answer:*
- `pop(i)` removes and returns the item at index `i`.
- `remove(x)` deletes the first occurrence of value `x`.
23. How do you merge two dictionaries in Python 3.9+?
- *Answer:* Using the `|` operator:
```python
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = dict1 | dict2 # {'a': 1, 'b': 2}
```

24. What is the output of `[x2 for x in range(5) if x % 2 == 0]`?


- *Answer:* `[0, 4, 16]` (Squares of even numbers 0, 2, 4).

25. How do you sort a list of tuples by the second element?


- *Answer:*
```python
lst = [(1, 4), (2, 1), (3, 2)]
lst.sort(key=lambda x: x[1]) # [(2, 1), (3, 2), (1, 4)]
```

26. What is the purpose of the `collections.defaultdict`?


- *Answer:* Provides a default value for missing keys.
Example:
```python
from collections import defaultdict
d = defaultdict(int) # Missing keys return 0
```

27. Write a Python code snippet to transpose a matrix (list of


lists).
- *Answer:*
```python
matrix = [[1, 2], [3, 4]]
transposed = list(zip(*matrix)) # [(1, 3), (2, 4)]
```

28. What is the difference between `dict.keys()` and


`dict.values()`?
- *Answer:*
- `keys()` returns a view of all keys.
- `values()` returns a view of all values.

29. How do you check if a list is empty?


- *Answer:*
```python
if not lst:
print("Empty")
```

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`.

2. Differentiate between `map()` and `filter()` functions with


examples.
- *Answer:*
- `map()` applies a function to all items in an iterable.
Example: `list(map(lambda x: x*2, [1, 2, 3]))` → `[2, 4, 6]`.
- `filter()` selects items based on a condition. Example:
`list(filter(lambda x: x > 1, [1, 2, 3]))` → `[2, 3]`.

3. What is recursion? Give an example of a recursive function.


- *Answer:* A function calling itself. Example:
```python
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
```

4. Explain the use of `*args` and `kwargs` in Python functions.


- *Answer:*
- `*args` allows variable-length positional arguments.
- `kwargs` allows variable-length keyword arguments.

5. How does the `reduce()` function work? Provide an example.


- *Answer:* Applies a rolling computation to sequential pairs.
Example:
```python
from functools import reduce
reduce(lambda x, y: x + y, [1, 2, 3]) # Output: 6
```

6. What is the difference between iteration and recursion?


- *Answer:* Iteration uses loops (e.g., `for`, `while`), while
recursion involves a function calling itself.

7. How do you return multiple values from a function in Python?


- *Answer:* Using tuples or lists. Example: `return a, b`
(returns a tuple).

8. What is a docstring? How is it written?


- *Answer:* A documentation string for functions/modules.
Written as `"""Function description"""`.

Modules and Packages


9. How do you import a module in Python? Give an example.
- *Answer:* Using `import`. Example: `import math`.
10. What is `__name__ == "__main__"` used for?
- *Answer:* Ensures code runs only when the script is executed
directly, not when imported.

11. How do you create a package in Python?


- *Answer:* By creating a directory with an `__init__.py` file
and modules inside.

12. What is the difference between `import module` and `from


module import *`?
- *Answer:*
- `import module` requires prefixing functions (e.g.,
`module.func()`).
- `from module import *` imports all functions directly (can
cause namespace pollution).

13. How do you install external packages in Python?


- *Answer:* Using `pip`. Example: `pip install numpy`.

14. What is the purpose of `__init__.py` in a package?


- *Answer:* It initializes the package and can contain
package-level code.

15. How do you reload an already imported module?


- *Answer:* Using `importlib.reload(module)` in Python 3.

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)`

17. Explain the concept of variable scope in Python with an


example demonstrating local and global variables.
- *Answer:*
```python
x = 10 # Global
def func():
y = 5 # Local
print(x + y)
func() # Output: 15
```

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)
```

19. What is function annotation in Python? Provide an example.


- *Answer:* Function annotations provide metadata about
parameters and return values.
```python
def greet(name: str) -> str:
return f"Hello {name}"
```

20. Write a recursive function to calculate the sum of digits of a


number.
- *Answer:*
```python
def sum_digits(n):
return n if n < 10 else n%10 + sum_digits(n//10)
print(sum_digits(123)) # Output: 6
```

21. How does Python's `nonlocal` keyword work? Provide an example.


- *Answer:* It allows modifying variables in the nearest
enclosing scope.
```python
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x) # Output: 20
```

22. What is a closure in Python? Demonstrate with an example.


- *Answer:* A closure is a function object that remembers
values in enclosing scopes.
```python
def outer(x):
def inner(y):
return x + y
return inner
add5 = outer(5)
print(add5(3)) # Output: 8
```

Modules and Packages


23. How would you create a Python module containing utility
functions? Show the structure.
- *Answer:*
```
# utils.py
def square(x):
return x2

def cube(x):
return x3
```

24. What is the purpose of `__all__` in a Python module? Give an


example.
- *Answer:* It specifies which symbols should be exported when
`from module import *` is used.
```python
# module.py
__all__ = ['public_func']
def public_func():
pass
def private_func():
pass
```

25. How do you handle cyclic imports in Python?


- *Answer:* Restructure code to avoid cycles, or move imports
inside functions.

26. Write a Python script that demonstrates importing a function


from a module in a package.
- *Answer:*
```
# mypackage/module.py
def useful_func():
return "Hello"

# main.py
from mypackage.module import useful_func
print(useful_func())
```

27. What is the difference between `import module` and `from


module import function`?
- *Answer:*
- `import module` requires `module.function()` syntax
- `from module import function` allows direct `function()`
calls

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`

29. What is the purpose of `if __name__ == '__main__'` in a


module?
- *Answer:* Ensures code only runs when the script is executed
directly, not when imported.

30. How do you access the docstring of an imported function


programmatically?
- *Answer:* Use `help(function)` or `function.__doc__`

### Unit IV: OOP, Exception Handling, and File Handling – Short
Answer Questions (2 Marks)

OOP (Classes and Objects)


1. What is a class and an object in Python?
- *Answer:* A class is a blueprint (e.g., `class Dog`), and an
object is an instance (e.g., `d = Dog()`).

2. Differentiate between class variables and instance variables.


- *Answer:* Class variables are shared across instances;
instance variables are unique to each object.

3. What is inheritance? Give an example.


- *Answer:* A child class inherits attributes/methods from a
parent class. Example:
```python
class Animal: pass
class Dog(Animal): pass
```

4. Explain operator overloading with an example.


- *Answer:* Defining custom behavior for operators. Example:
```python
def __add__(self, other): return self.x + other.x
```

5. What is the `self` keyword in Python classes?


- *Answer:* Refers to the instance of the class (like `this`
in other languages).

6. What is containership in Python?


- *Answer:* One class containing an object of another class
(has-a relationship).

7. How do you make a class member private in Python?


- *Answer:* Prefix with `__` (e.g., `__private_var`).

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.

10. How do you raise a custom exception?


- *Answer:* Using `raise`. Example: `raise ValueError("Invalid
input")`.

11. What is the purpose of the `else` block in exception handling?


- *Answer:* Executes if no exception occurs in the `try`
block.

File Handling
12. What are the different file modes in Python?
- *Answer:* `"r"` (read), `"w"` (write), `"a"` (append),
`"r+"` (read+write).

13. How do you read a file line by line in Python?


- *Answer:*
```python
with open("file.txt") as f:
for line in f: print(line)
```

14. What is the advantage of using `with` in file handling?


- *Answer:* Automatically closes the file after the block,
even if an error occurs.

15. How do you write a list to a file in Python?


- *Answer:*
```python
with open("file.txt", "w") as f:
f.write("\n".join(["line1", "line2"]))
```

---

OOP (Classes and Objects)


16. What is method overriding in Python? Provide an example.
- *Answer:* Redefining a parent class method in child class.
```python
class Parent:
def show(self):
print("Parent")

class Child(Parent):
def show(self):
print("Child")
```

17. Explain the concept of abstract base classes in Python.


- *Answer:* ABCs define a blueprint for other classes using
the `abc` module.

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

20. Write a Python class demonstrating multiple inheritance.


- *Answer:*
```python
class A:
pass

class B:
pass

class C(A, B):


pass
```

Exception Handling
21. How would you create a custom exception class in Python?
- *Answer:*
```python
class MyError(Exception):
pass
```

22. What is the purpose of the `finally` block in exception


handling?
- *Answer:* Code in `finally` always executes, regardless of
exceptions.

23. Write a Python code snippet that raises a custom exception


when a negative number is input.
- *Answer:*
```python
def check_positive(n):
if n < 0:
raise ValueError("Negative number not allowed")
```

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)

26. Write a Python function to append text to a file.


- *Answer:*
```python
def append_to_file(filename, text):
with open(filename, 'a') as f:
f.write(text)
```

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)
```

28. What is the advantage of using `pathlib` over traditional file


operations?
- *Answer:* Provides object-oriented interface and cross-
platform path handling.

29. Write a Python script to copy the contents of one file to


another.
- *Answer:*
```python
with open('source.txt') as src, open('dest.txt', 'w') as dst:
dst.write(src.read())
```
30. How do you check if a file exists before attempting to open
it?
- *Answer:*
```python
import os
if os.path.exists('file.txt'):
with open('file.txt') as f:
pass
```

Short Notes Question Bank with Answers for


Python Programming (MCA)
Unit I: Python Basics and Strings (3 Marks Each)
1. Explain the signi cance of Python as a high-level programming language.
Answer: Python is a high-level, interpreted programming language known for its simplicity
and readability. It uses English-like syntax, making it easy to learn and write code. Python
supports multiple programming paradigms (procedural, object-oriented, functional) and has
a vast standard library for tasks like web development, data analysis, and automation. Its
versatility and ease of use make it popular for beginners and professionals.

2. Describe the process of installing and setting up Python on a Windows system.


Answer: To install Python on Windows: 1) Download the latest Python installer from
python.org. 2) Run the installer, ensuring to check "Add Python to PATH." 3) Select "Install
Now" or customize the installation. 4) Verify installation by typing over python --
version in Command Prompt. 5) Use IDLE or an IDE like PyCharm to write and run
Python code.

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 @, #.

4. Differentiate between keywords and identi ers in Python with examples.


Answer: Keywords are reserved words with special meanings, e.g., if, for, while.
They cannot be used as identi ers. Identi ers are user-de ned names for variables,
functions, etc., e.g., total, my_function. Example: if (keyword) controls a
condition, while age (identi er) names a variable.

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).

7. Explain how dynamic typing works in Python with an example.


Answer: Dynamic typing means variable types are determined at runtime, not declared.
Example: x = 5 (integer); x = "Hello" (string). Python reassigns x to a new type
without explicit type declaration, making coding exible but requiring care to avoid type
errors.

8. Discuss the precedence of arithmetic operators in Python with examples.


Answer: Operator precedence determines the order of operations: 1) Parentheses (), 2)
Exponentiation **, 3) Multiplication *, Division /, Floor Division //, Modulus %, 4)
Addition +, Subtraction -. Example: 3 + 4 * 2 = 11 (multiplication rst), but (3 +
4) * 2 = 14 (parentheses rst).

9. Explain the concept of associativity in Python's arithmetic operations.


Answer: Associativity de nes the order of evaluation for operators with the same
precedence. Most arithmetic operators (+, -, *, /) are left-to-right associative. Example:
10 - 5 - 2 = (10 - 5) - 2 = 3. Exponentiation (**) is right-to-left: 2
**listen ** 3 ** 2 = 2 ** (3 ** 2) = 8.

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.

13. Discuss the importance of comments in Python and their types.


Answer: Comments explain code, improving readability. Types: 1) Single-line: Starts with
#, e.g., # This is a comment. 2) Multi-line: Uses triple quotes """ or ''', e.g.,
"""Multi-line comment""". They are ignored by the interpreter but aid
debugging and collaboration.
fi
fl
fi
fl
fl
fi
14. Explain multi-line statements in Python with an example.
Answer: Multi-line statements split a single statement across lines using \ or parentheses.
Example: total = (1 + 2 + 3 + \ 4 + 5). Parentheses allow natural line
breaks without \. This improves code readability for long expressions.

15. Describe the properties of strings in Python.


Answer: Strings are immutable sequences of characters, enclosed in ', ", or """.
Properties: 1) Immutable (cannot change individual characters). 2) Ordered (supports
indexing). 3) Supports slicing, concatenation, and repetition. Example: s = "Python";
s[0] = "P" but s[0] = "J" fails.

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.

19. Explain string concatenation and repetition with examples.


Answer: Concatenation combines strings using +, e.g., "Py" + "thon" yields
"Python". Repetition repeats a string using *, e.g., "Hi" * 3 yields "HiHiHi".
Both operations create new strings due to string immutability.

20. Discuss the strip() method and its variants in Python.


Answer: strip() removes leading/trailing whitespace, e.g., " Hello ".strip()
returns "Hello". Variants: lstrip() removes only leading whitespace; rstrip()
removes trailing whitespace. Optional arguments specify characters to remove, e.g.,
strip("x").

21. Explain how strings are compared in Python with examples.


Answer: Strings are compared lexicographically using ASCII/Unicode values. Example:
"apple" < "banana" is True (a < b). Case matters: "Apple" < "apple" is
True. Operators: <, >, ==, etc., are used for sorting or validation.

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.

25. Discuss the split() method for strings with an example.


Answer: The split() method splits a string into a list using a delimiter (default:
whitespace). Example: "a b c".split() returns ["a", "b", "c"]. Specify
delimiter, e.g., "a,b,c".split(",") returns ["a", "b", "c"].

26. Explain the concept of string immutability in Python.


Answer: Strings are immutable, meaning their characters cannot be changed after creation.
Example: s = "Python"; s[0] = "J" raises an error. Operations like
concatenation create new strings, ensuring data integrity but requiring memory for new
objects.

27. Describe the join() method for strings with an example.


Answer: The join() method combines a list of strings into one, using a separator.
Example: "-".join(["a", "b", "c"]) returns "a-b-c". The separator is the
string on which join() is called, e.g., " ".join(["Hello", "World"])
yields "Hello World".

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.

29. Explain the role of the str() function in type conversion.


Answer: The str() function converts a value to a string. Example: str(42) returns
"42"; str(3.14) returns "3.14". It’s used for concatenation or formatting, ensuring
compatibility with string operations.

30. Discuss formatted printing using f-strings in Python with an example.


Answer: F-strings allow embedding expressions in strings using f"...". Example: name
= "Alice"; print(f"Hi, {name}") outputs Hi, Alice. They are concise,
readable, and support expressions like f"Sum: {2 + 3}" (outputs Sum: 5).

Unit II: Control Structures and Data Structures (3 Marks


Each)
1. Explain the role of logical operators in decision control instructions.
Answer: Logical operators (and, or, not) combine conditions in decision-making. and
fi
fi
returns True if both conditions are true, e.g., x > 0 and x < 10. or returns True
if at least one is true, e.g., x < 0 or x > 10. not negates, e.g., not True is
False.

2. Discuss conditional expressions in Python with an example.


Answer: Conditional expressions (ternary operators) provide concise if-else logic. Syntax:
value_if_true if condition else value_if_false. Example:
status = "Adult" if age >= 18 else "Minor". It simpli es code for
single-line decisions.

3. Write a short note on the all() and any() functions in Python.


Answer: all() returns True if all elements in an iterable are true, e.g., all([True,
True, False]) is False. any() returns True if at least one element is true, e.g.,
any([False, True, False]) is True. Useful for condition checks in lists.

4. Explain the use of the pass statement in Python with an example.


Answer: The pass statement is a no-op placeholder for empty blocks. Example: if x >
0: pass does nothing if x > 0. It’s used to maintain syntax when no action is needed,
often during code development.

5. Describe the difference between for and while loops in Python.


Answer: for loops iterate over a sequence (e.g., for i in range(5):
print(i) prints 0 to 4). while loops run until a condition is false (e.g., x = 0;
while x < 5: print(x); x += 1). for is for known iterations; while for
condition-based loops.

6. Discuss the use of the break statement in loops with an example.


Answer: The break statement exits a loop immediately. Example: for i in
range(10): if i == 5: break; print(i) prints 0 to 4. It’s used to stop
loops when a condition is met, like nding an item.

7. Explain the role of the continue statement in loops with an example.


Answer: The continue statement skips the rest of the current loop iteration. Example:
for i in range(5): if i == 2: continue; print(i) skips 2,
printing 0, 1, 3, 4. It’s used to bypass speci c iterations.

8. Write a short note on the else block with loops in Python.


Answer: The else block in loops runs if the loop completes without a break. Example:
for i in range(5): if i > 10: break; else: print("No
break") prints No break. It’s useful for checking if a loop ran fully.

9. Explain how to create and initialize a list in Python.


Answer: Lists are created using square brackets [] or list(). Initialization examples:
my_list = [1, 2, 3] or my_list = list(range(3)) creates [0, 1,
2]. Lists are mutable, ordered, and allow mixed data types.

10. Discuss accessing list elements using indexing and slicing.


Answer: Indexing accesses a single element, e.g., my_list = [10, 20, 30];
fi
fi
fi
my_list[1] returns 20. Slicing extracts a sublist, e.g., my_list[1:3] returns
[20, 30]. Negative indices count from the end, e.g., my_list[-1] is 30.

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.

12. Explain the append() and extend() methods for lists.


Answer: append() adds a single element to a list’s end, e.g., my_list = [1, 2];
my_list.append(3) results in [1, 2, 3]. extend() adds multiple elements
from an iterable, e.g., my_list.extend([4, 5]) results in [1, 2, 3, 4,
5].

13. Write a short note on list concatenation and repetition.


Answer: Concatenation combines lists using +, e.g., [1, 2] + [3, 4] yields [1,
2, 3, 4]. Repetition repeats a list using *, e.g., [1, 2] * 2 yields [1, 2, 1,
2]. Both create new lists, preserving originals.

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].

15. Explain the concept of list comprehension in Python with an example.


Answer: List comprehension creates a new list concisely. Syntax: [expression for
item in iterable]. Example: [x**2 for x in range(3)] yields [0,
1, 4]. It’s compact and readable for transforming/ ltering lists.

16. Describe how to create and initialize a set in Python.


Answer: Sets are created using curly braces {} or set(). Example: my_set = {1,
2, 3} or my_set = set([1, 2, 2]) creates {1, 2, 3} (duplicates
removed). Sets are unordered, mutable, and store unique elements.

17. Discuss the mathematical operations (union, intersection) on sets.


Answer: Union (|) combines all elements, e.g., {1, 2} | {2, 3} yields {1, 2,
3}. Intersection (&) keeps common elements, e.g., {1, 2} & {2, 3} yields {2}.
These operations are useful for comparing datasets.

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.

19. Explain how to loop through a set in Python with an example.


Answer: A for loop iterates over set elements (unordered). Example: my_set = {1,
2, 3}; for x in my_set: print(x) prints 1, 2, 3 (order may vary). It’s used
for processing unique elements.
fi
fi
20. Describe the properties of tuples and their immutability.
Answer: Tuples are immutable, ordered sequences de ned with (). Example: t = (1,
2, 3); t[0] = 5 raises an error. Properties: 1) Immutable (cannot modify). 2) Ordered
(supports indexing). 3) Allows duplicates. Useful for xed data.

21. Discuss accessing tuple elements using indexing and slicing.


Answer: Indexing accesses one element, e.g., t = (10, 20, 30); t[1] returns
20. Slicing extracts a subtuple, e.g., t[1:3] returns (20, 30). Negative indices work,
e.g., t[-1] is 30.

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.

23. Write a short note on creating and initializing a dictionary in Python.


Answer: Dictionaries store key-value pairs, created with {} or dict(). Example: d =
{"a": 1, "b": 2} or d = dict(a=1, b=2). Keys are unique and immutable;
values can be any type. Useful for fast lookups.

24. Discuss accessing key-value pairs in a dictionary with an example.


Answer: Access values using keys in square brackets or get(). Example: d = {"a":
1, "b": 2}; d["a"] returns 1. d.get("b") returns 2; get() returns None
for missing keys, avoiding errors.

25. Explain looping through a dictionary using a for loop.


Answer: Loop over keys with for key in dict:. Example: d = {"a": 1,
"b": 2}; for k in d: print(k, d[k]) prints a 1, b 2. Use items()
for key-value pairs: for k, v in d.items(): print(k, v).

26. Describe the get() and setdefault() methods for dictionaries.


Answer: get() retrieves a value or a default if the key is missing, e.g., d = {"a":
1}; d.get("b", 0) returns 0. setdefault() gets a value or sets it if absent,
e.g., d.setdefault("b", 2) adds "b": 2 if "b" is missing.

27. Write a short note on dictionary comprehension in Python.


Answer: Dictionary comprehension creates a dictionary concisely. Syntax: {key:
value for item in iterable}. Example: {x: x**2 for x in
range(3)} yields {0: 0, 1: 1, 2: 4}. It’s ef cient for transforming data into
key-value pairs.

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.

30. Explain set comprehension in Python with an example.


Answer: Set comprehension creates a set concisely. Syntax: {expression for
item in iterable}. Example: {x**2 for x in range(3)} yields {0,
1, 4}. It ensures unique elements and is useful for ltering/transforming data.

Unit III: Functions, Modules, and Packages (3 Marks Each)


1. Explain the signi cance of functions in Python programming.
Answer: Functions are reusable blocks of code that perform speci c tasks, improving
modularity and code organization. They reduce redundancy and make code easier to
maintain. Example: def add(a, b): return a + b de nes a function to add
numbers, callable as add(2, 3) to get 5.

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.

4. Explain how to invoke a function in Python with different argument types.


Answer: Functions are invoked using function_name(arguments). Argument
types: 1) Positional: add(2, 3). 2) Keyword: add(a=2, b=3). 3) Default: def
greet(name="Guest"): ... uses "Guest" if no argument is given. Example:
greet() or greet("Alice").

5. Write a short note on default arguments in Python functions.


Answer: Default arguments have preset values used if no argument is provided. De ned in
the function header, e.g., def greet(name="World"): return f"Hello,
{name}". Calling greet() returns Hello, World; greet("Alice") returns
Hello, Alice. They enhance exibility.

6. Discuss the concept of keyword arguments in Python with an example.


Answer: Keyword arguments specify arguments by parameter names, allowing any order.
Example: def info(name, age): return f"{name} is {age}". Call:
info(age=25, name="Alice") returns Alice is 25. They improve
readability and avoid argument order errors.
fi
fi
fi
fi
fl
fi
fi
fi
fi
fi
fi
fi
fi
fi
7. Explain the use of variable-length arguments (*args) in Python functions.
Answer: *args allows a function to accept any number of positional arguments as a tuple.
Example: def sum_all(*args): return sum(args). Calling
sum_all(1, 2, 3) returns 6. It’s useful for exible argument counts.

8. Describe the role of **kwargs in Python functions with an example.


Answer: **kwargs accepts variable keyword arguments as a dictionary. Example: def
details(**kwargs): return kwargs. Calling
details(name="Alice", age=25) returns {'name': 'Alice',
'age': 25}. It’s used for handling named arguments dynamically.

9. Write a short note on recursive functions in Python.


Answer: Recursive functions call themselves to solve problems. Example: def
factorial(n): return 1 if n == 0 else n * factorial(n-1).
factorial(5) returns 120. They simplify code for problems like factorials but may
cause stack over ow for large inputs.

10. Discuss the advantages and disadvantages of recursion vs. iteration.


Answer: Advantages of recursion: Cleaner code for problems like tree traversal; easier to
understand. Disadvantages: Higher memory use (call stack), slower for large inputs.
Iteration: Faster, memory-ef cient but may require complex logic. Example: Recursive
factorial vs. loop-based factorial.

11. Explain the concept of lambda functions in Python with an example.


Answer: Lambda functions are anonymous, single-expression functions. Syntax: lambda
arguments: expression. Example: double = lambda x: x * 2;
double(5) returns 10. They’re concise for simple operations, often used with map()
or filter().

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.

13. Write a short note on the filter() function in Python.


Answer: filter() applies a function to an iterable, keeping elements where the function
returns True. Example: list(filter(lambda x: x % 2 == 0, [1, 2,
3, 4])) returns [2, 4]. It’s used for selecting elements based on conditions.

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.

15. Discuss the concept of function argument unpacking in Python.


Answer: Argument unpacking uses * for lists/tuples and ** for dictionaries. Example: def
add(a, b): return a + b; nums = [1, 2]; add(*nums) returns 3.
fl
fi
fi
fl
For dictionaries: d = {"a": 1, "b": 2}; add(**d) works similarly. It
simpli es passing arguments.

16. Explain the role of the __main__ module in Python programs.


Answer: __main__ is the name of the main module when a Python le runs directly.
Using if __name__ == "__main__": ensures code runs only when the le is
executed, not when imported. Example: if __name__ == "__main__":
print("Running") prints only if run directly.

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.

19. Explain the concept of creating a Python module with an example.


Answer: A module is a .py le with functions, variables, or classes. Example: Create
mymod.py with def greet(): return "Hello". Import it: import
mymod; print(mymod.greet()) outputs Hello. Modules promote code
organization and reuse.

20. Discuss the difference between a module and a package in Python.


Answer: A module is a single .py le (e.g., mymod.py). A package is a directory with an
__init__.py le containing multiple modules. Example: Package mypackage with
mod1.py and mod2.py. Modules are les; packages organize multiple modules.

21. Describe how to create and use a package in Python.


Answer: Create a directory (e.g., mypackage) with an __init__.py le (can be
empty) and module les. Example: mypackage/mod.py with def hi():
return "Hi". Use: from mypackage.mod import hi; print(hi())
outputs Hi. Packages organize related modules.

22. Explain the role of the __init__.py le in Python packages.


Answer: The __init__.py le marks a directory as a package and runs when the
package is imported. It can be empty or contain initialization code, e.g., from .mod
import hi. It enables package imports like from mypackage import mod.

23. Write a short note on the sys module in Python.


Answer: The sys module provides system-speci c functions and variables. Examples:
sys.version (Python version), sys.argv (command-line arguments),
sys.exit() (terminates program). It’s used for interacting with the Python interpreter
and environment.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
24. Discuss the math module and its commonly used functions.
Answer: The math module provides mathematical functions. Common functions:
math.sqrt(x) (square root), math.factorial(n) (factorial), math.pi
(constant). Example: import math; math.sqrt(16) returns 4.0;
math.factorial(5) returns 120.

25. Explain how to alias a module during import with an example.


Answer: Aliasing renames a module using as. Example: import math as m;
print(m.pi) outputs 3.14159. It shortens module names, improving readability and
reducing typing in large programs.

26. Describe the concept of relative imports in Python packages.


Answer: Relative imports use . (current package) or .. (parent package) to import
modules within a package. Example: In mypackage/mod1.py, use from .mod2
import func to import func from mod2.py. They simplify imports within
packages.

27. Write a short note on the random module in Python.


Answer: The random module provides functions for random number generation.
Examples: random.randint(1, 10) (random integer), random.choice([1,
2, 3]) (random element). It’s used for simulations, games, and random sampling.

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.

Unit IV: OOP, Exception Handling, and File Handling (3


Marks Each)
1. Explain the concept of Object-Oriented Programming (OOP) in Python.
Answer: OOP organizes code using objects and classes, focusing on data and behavior. Key
concepts: encapsulation, inheritance, polymorphism. Example: A Car class with attributes
(speed) and methods (drive). It improves modularity and reusability.
fl
2. Discuss the difference between procedural and object-oriented programming.
Answer: Procedural programming uses functions and sequential steps (e.g., def
calculate()). OOP uses classes/objects, combining data and methods (e.g., class
Car: def drive(self): ...). OOP supports inheritance and encapsulation;
procedural is simpler but less modular.

3. Describe the role of classes and objects in Python with an example.


Answer: A class is a blueprint for objects, de ning attributes and methods. An object is an
instance of a class. Example: class Dog: def bark(self): return
"Woof". Object: d = Dog(); d.bark() returns Woof. Classes model real-world
entities.

4. Explain the concept of public and private members in Python classes.


Answer: Public members are accessible everywhere (e.g., self.name). Private
members, pre xed with __, are restricted (e.g., self.__age). Example: class
Person: def __init__(self): self.__age = 25. Accessing __age
directly raises an error; use methods for access.

5. Write a short note on the __init__ method in Python classes.


Answer: The __init__ method is a constructor, called when an object is created. It
initializes instance variables. Example: class Student: def
__init__(self, name): self.name = name. s =
Student("Alice") sets s.name to Alice.

6. Discuss how to create and instantiate objects in Python.


Answer: De ne a class with class Name:, then instantiate using Name(). Example:
class Car: def __init__(self, model): self.model = model.
Instantiate: c = Car("Toyota"). c is an object with model set to Toyota.

7. Explain the concept of class variables in Python with an example.


Answer: Class variables are shared across all instances of a class. Example: class Dog:
count = 0; def __init__(self): Dog.count += 1. Creating d1 =
Dog(); d2 = Dog() makes Dog.count equal 2. They track shared data.

8. Describe the role of instance methods in Python classes.


Answer: Instance methods operate on an object’s data, taking self as the rst parameter.
Example: class Car: def drive(self, speed): self.speed =
speed. Calling c = Car(); c.drive(60) sets c.speed to 60. They de ne
object behavior.

9. Write a short note on operator overloading in Python.


Answer: Operator overloading allows custom behavior for operators like +. Example:
class Vector: def __init__(self, x): self.x = x; def
__add__(self, other): return Vector(self.x + other.x). v1
= Vector(2); v2 = Vector(3); v3 = v1 + v2 sets v3.x to 5.

10. Explain the concept of containership in Python with an example.


Answer: Containership is when a class contains objects of another class. Example: class
Engine: def __init__(self, hp): self.hp = hp; class Car:
fi
fi
fi
fi
fi
def __init__(self): self.engine = Engine(100). c = Car()
has an Engine object in c.engine.

11. Discuss the features of inheritance in Python.


Answer: Inheritance allows a class to inherit attributes and methods from another. Features:
code reuse, extensibility, hierarchy. Example: class Animal: def eat(self):
pass; class Dog(Animal): .... Dog inherits eat(). Supports single,
multiple, and multilevel inheritance.

12. Describe single inheritance in Python with an example.


Answer: Single inheritance involves one parent class. Example: class Animal: def
eat(self): return "Eating"; class Dog(Animal): def
bark(self): return "Woof". d = Dog(); d.eat() returns Eating. It
promotes code reuse with one base class.

13. Explain multiple inheritance in Python and its challenges.


Answer: Multiple inheritance allows a class to inherit from multiple parents. Example:
class A: def m(self): pass; class B: def m(self): pass;
class C(A, B): pass. Challenge: The diamond problem (ambiguity in method
resolution). Python uses Method Resolution Order (MRO).

14. Write a short note on multilevel inheritance in Python.


Answer: Multilevel inheritance involves a chain of classes. Example: class Animal:
def eat(self): pass; class Mammal(Animal): pass; class
Dog(Mammal): pass. Dog inherits from Mammal, which inherits from Animal. It
creates a hierarchy but can complicate design.

15. Discuss the use of the super() function in Python inheritance.


Answer: super() calls a parent class’s method. Example: class Animal: def
__init__(self): self.type = "Animal"; class Dog(Animal):
def __init__(self): super().__init__(); self.breed =
"Lab". d = Dog() sets d.type and d.breed. It ensures parent initialization.

16. Explain the concept of exceptions in Python programming.


Answer: Exceptions are errors that disrupt program execution, e.g.,
ZeroDivisionError. They’re handled to prevent crashes. Example: Dividing by zero
raises an exception. Python uses try-except to manage exceptions gracefully.

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.

18. Write a short note on handling multiple exceptions in Python.


Answer: Multiple exceptions are handled using multiple except blocks or a tuple.
Example: try: x = int("abc"); except (ValueError,
TypeError): print("Invalid input"). This catches both ValueError
and TypeError, allowing speci c error handling.
fi
19. Explain how to create a user-de ned exception in Python.
Answer: Create a custom exception by subclassing Exception. Example: class
MyError(Exception): pass; raise MyError("Custom error").
This raises MyError with a message. It’s used for application-speci c error handling.

20. Discuss the role of the else block in exception handling.


Answer: The else block runs if no exception occurs in try. Example: try: x =
1 / 1; except ZeroDivisionError: print("Error"); else:
print("Success") prints Success. It separates normal ow from error handling.

21. Explain the finally block and its use in Python.


Answer: The finally block runs regardless of exceptions. Example: try: x = 1 /
0; except: print("Error"); finally: print("Cleanup") prints
Error and Cleanup. It’s used for cleanup tasks like closing les.

22. Describe the process of opening a le in Python with different modes.


Answer: Use open(filename, mode). Modes: "r" (read, default), "w" (write,
overwrites), "a" (append), "rb"/"wb" (binary read/write). Example: f =
open("file.txt", "r") opens for reading. Modes determine le access behavior.

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.

24. Explain how to write data to a le in Python with an example.


Answer: Use write() to write strings to a le opened in "w" or "a" mode. Example: f
= open("file.txt", "w"); f.write("Hello") writes Hello to
file.txt. Use writelines() for lists of strings. Close with f.close().

25. Discuss the use of the with statement in le handling.


Answer: The with statement ensures a le is closed after use, even if an error occurs.
Example: with open("file.txt", "r") as f: print(f.read()). It
simpli es le handling, avoiding explicit close() calls.

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.

27. Explain the seek() and tell() methods in le handling.


Answer: seek(offset) moves the le pointer to offset. tell() returns the
current pointer position. Example: f = open("file.txt", "r");
f.seek(5); print(f.tell()) prints 5. They’re used for navigating les.

28. Write a short note on handling le-related exceptions in Python.


Answer: File operations may raise exceptions like FileNotFoundError or
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fl
fi
fi
fi
fi
fi
IOError. Handle with try-except. Example: try: f =
open("file.txt"); except FileNotFoundError: print("File
not found"). This prevents crashes during le access.

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.

30. Explain how to append data to an existing le in Python.


Answer: Open a le in "a" mode and use write(). Example: f =
open("file.txt", "a"); f.write("New line\n") adds New line
to file.txt without overwriting. Use with for safer appending.

————————————————————————————————————————
——————————————5. CODE
—————————————————————————— —————————————
———————————————

Unit I: Python Basics and Strings


1. Write a Python program to check if a given number is even or odd. Print appropriate
message.
Answer:

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.)

11. Write a Python program to print the ASCII value of a character.


Answer:

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}.")

Unit II: Control Structures and Data Structures


1. Write a Python program to print all prime numbers between two given numbers.
Answer:

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

start = int(input("Enter start: "))


end = int(input("Enter end: "))
print("Prime numbers in range:")
for num in range(start, end+1):
if is_prime(num):
print(num, end=" ")
2. Write a Python program to print the Fibonacci series up to n terms.
Answer:
python
# Program to print Fibonacci series up to n terms
n = int(input("Enter number of terms: "))
a, b = 0, 1
print("Fibonacci series:")
for _ in range(n):
print(a, end=" ")
a, b = b, a+b
3. Write a Python program to nd the factorial of a number using recursion.
Answer:

python
# Program to find factorial using recursion
def factorial(n):
if n == 1 or n == 0:
return 1
else:
return n * factorial(n-1)

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


print(f"Factorial of {num} is {factorial(num)}")
4. Write a Python program to check if a number is an Armstrong number.
Answer:

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)

Unit II: Control Structures and Data Structures


1. Write a Python program to nd the sum of all even numbers between two user-input
integers.
Answer:

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)

lst = list(map(int, input("Enter list elements: ").split()))


print("Largest element:", find_max(lst))
10. Write a Python program to print all prime numbers in a given range using a function.
Answer:

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

start = int(input("Enter start: "))


end = int(input("Enter end: "))
print("Prime numbers in range:")
for num in range(start, end+1):
if is_prime(num):
print(num, end=" ")
11. Write a Python program to create a dictionary from two lists, one for keys and another for
values.
Answer:

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

ops = {'+': add, '-': sub, '*': mul, '/': div}


a = float(input("Enter first number: "))
op = input("Enter operator (+, -, *, /): ")
b = float(input("Enter second number: "))
if op in ops:
print("Result:", ops[op](a, b))
else:
print("Invalid operator")

Unit IV: OOP, Exception Handling, and File Handling


1. Write a Python program to de ne a class Student with attributes name and rollno. Create
two objects and display their details.
Answer:

python
# Program to define Student class and display objects
class Student:
def __init__(self, name, rollno):
self.name = name
self.rollno = rollno

stu1 = Student("Alice", 101)


stu2 = Student("Bob", 102)
print("Student 1:", stu1.name, stu1.rollno)
print("Student 2:", stu2.name, stu2.rollno)
2. Write a Python program to demonstrate inheritance: create a base class Animal and a
derived class Dog with a method to display the sound.
Answer:

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

age = int(input("Enter age: "))


fi
fi
fi
fi
fi
if age < 0:
raise NegativeAgeError("Age cannot be negative")
else:
print("Age is:", age)
7. Write a Python program to demonstrate operator overloading for addition of two objects of
a class.
Answer:

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)

obj = MyClass(10, 20)


obj.display()
18. Write a Python program to count the number of lines, words, and characters in a le.
Answer:

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")

Unit III: Functions, Modules, and Packages


1. Write a Python function to calculate the factorial of a number using recursion. Call the
function for a user input value and print the result.
Answer:

python
# Function to calculate factorial using recursion
def factorial(n):
if n == 1 or n == 0:
return 1
else:
return n * factorial(n-1)

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


print(f"Factorial of {num} is {factorial(num)}")
2. Write a Python function to check if a number is prime. Use the function to print all prime
numbers between two user-input numbers.
Answer:

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

start = int(input("Enter start: "))


end = int(input("Enter end: "))
print("Prime numbers in range:")
for num in range(start, end+1):
if is_prime(num):
print(num, end=" ")
3. Write a Python function to reverse a list. Use the function to reverse a user-input list.
Answer:

python
# Function to reverse a list
def reverse_list(lst):
return lst[::-1]

lst = input("Enter list elements (space-separated):


").split()
print("Reversed list:", reverse_list(lst))
4. Write a Python function that accepts a string and returns the number of vowels and
consonants in it.
Answer:

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

s = input("Enter a string: ")


v, c = count_vowels_consonants(s)
print(f"Vowels: {v}, Consonants: {c}")
5. Write a Python function to nd the maximum and minimum elements in a list. Use the
function for a user-input list.
Answer:

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:])

lst = list(map(int, input("Enter numbers (space-separated):


").split()))
print(f"Sum: {sum_list(lst)}")
7. Write a Python function to generate the Fibonacci series up to n terms. Call the function for
a user input value and print the series.
Answer:

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

n = int(input("Enter number of terms: "))


print("Fibonacci series:", fibonacci(n))
8. Write a Python function that accepts a list and returns a new list with all even numbers
from the original list.
Answer:

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))

lst = list(map(int, input("Enter numbers (space-separated):


").split()))
print("Squared list:", square_list(lst))
10. Write a Python function using lter() to extract all strings longer than a given length from
a list. Use the function for a user-input list and length.
Answer:

python
# Function to filter strings longer than given length
def filter_long_strings(lst, length):
return list(filter(lambda s: len(s) > length, lst))

lst = input("Enter strings (comma-separated): ").split(',')


length = int(input("Enter length: "))
print("Filtered strings:", filter_long_strings(lst, length))
11. Write a Python function using reduce() to nd the product of all elements in a list. Use the
function for a user-input list.
Answer:

python
# Function to find product using reduce
from functools import reduce

def product_list(lst):
return reduce(lambda x, y: x * y, lst)

lst = list(map(int, input("Enter numbers (space-separated):


").split()))
print("Product:", product_list(lst))
12. Write a Python function to count the frequency of each word in a string. Return a
dictionary with words as keys and their counts as values.
Answer:
fi
fi
python
# Function to count word frequency
def word_frequency(s):
words = s.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq

s = input("Enter a string: ")


print("Word frequency:", word_frequency(s))
13. Write a Python function to sort a list of tuples based on the second element of each tuple.
Use the function for a user-input list of tuples.
Answer:

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])

tup_list = eval(input("Enter list of tuples (e.g., [(1,2),


(3,1)]): "))
print("Sorted list:", sort_by_second(tup_list))
14. Write a Python function that takes a variable number of arguments and returns the sum
of all the arguments.
Answer:

python
# Function to sum variable number of arguments
def sum_args(*args):
return sum(args)

print("Sum:", sum_args(10, 20, 30))


15. Write a Python lambda function that returns the square of a number. Use the lambda
function to print squares of numbers from 1 to 10.
Answer:

python
# Lambda function to return square of a number
square = lambda x: x**2

for i in range(1, 11):


print(square(i), end=" ")
16. Write a Python function to create a module named 'math_ops' containing functions for
add, subtract, multiply, and divide. Import and use it in another script.
Answer:

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

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


b = int(input("Enter second number: "))
print("Addition:", math_ops.add(a, b))
print("Subtraction:", math_ops.subtract(a, b))
print("Multiplication:", math_ops.multiply(a, b))
print("Division:", math_ops.divide(a, b))
17. Write a Python function to create a package named 'utils' with a module 'string_ops'
containing functions to count vowels and reverse a string. Import and use it in another script.
Answer:

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

s = input("Enter a string: ")


print("Vowels:", count_vowels(s))
print("Reversed:", reverse_string(s))
18. Write a Python function to demonstrate the difference between local and global variables.
Answer:
python
# Function to demonstrate local and global variables
global_var = 10

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)

n = int(input("Enter term: "))


print(f"{n}th Fibonacci term:", fibonacci(n))
————————————————————————————————————————
——————————————6. OUTPUT ————————————————————

——————————————————————————————————————-

Predict the Output Question Bank with


Answers for Python Programming (MCA)
Unit I: Python Basics and Strings (2 Marks Each)
Question: Predict the output of the following code:
x = 5

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}!")

Answer: Hi, Alice!


Dry Run: name = "Alice". F-string f"Hi, {name}!" embeds Alice into the string,
resulting in Hi, Alice!. Output is Hi, Alice!.
Question: Predict the output of the following code:
x = input("Enter: ") # User enters 123

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: ['Hello', 'World']


Dry Run: s = "Hello,World". split(",") splits the string at ,, creating a list
["Hello", "World"]. Output is ['Hello', 'World'].
Question: Predict the output of the following code:
print("abc" < "def")

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: True False


fl
Dry Run: x = 5, y = "5". int(y) = 5. x == int(y) checks equality (5 == 5), so
True. x is int(y) checks identity (different objects), so False. Output is True False.
Unit II: Control Structures and Data Structures (2 Marks
Each)
Question: Predict the output of the following code:
x = 5

if x > 3 and x < 7:


print("Yes")
else:
print("No")

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):

print(i, end=" ")

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).

Unit III: Functions, Modules, and Packages (2 Marks Each)


Question: Predict the output of the following code:
def add(a, b=2):

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 f"Hi, {name}!"


print(greet(name="Alice"))

Answer: Hi, Alice!


Dry Run:
greet(name) takes a parameter name.
greet(name="Alice") uses a keyword argument, setting name="Alice".
f"Hi, {name}!" returns Hi, Alice!.
Output is Hi, Alice!.
Question: Predict the output of the following code:
def sum_nums(*args):

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))

Answer: {'x': 1, 'y': 2}


Dry Run:
info(**kwargs) accepts keyword arguments as a dictionary.
info(x=1, y=2) passes x=1, y=2, so kwargs = {"x": 1, "y": 2}.
return kwargs outputs the dictionary.
Output is {'x': 1, 'y': 2}.
fi
Question: Predict the output of the following code:
def fact(n):

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]

print(list(map(lambda x: x**2, nums)))

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

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

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:

def __init__(self, model):


self.model = model
c = Car("Toyota")
print(c.model)

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:

def __init__(self, x):


self.x = x
def __add__(self, other):
return Vector(self.x + other.x)
v1 = Vector(2)
v2 = Vector(3)
print((v1 + v2).x)

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:

def __init__(self, item):


fi
self.item = item
b = Box("Toy")
print(b.item)

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")

Answer: Out of range


Dry Run:
lst[2] accesses index 2, but lst = [1, 2] has only indices 0, 1, raising
IndexError.
except IndexError prints "Out of range".
Output is Out of range.
Question: Predict the output of the following code:
class A:

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:

def __init__(self, x):


self.__x = x
def get_x(self):
return self.__x
p = Point(5)
print(p.get_x())

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")

Answer: Not found


Dry Run:
open("no_file.txt") raises FileNotFoundError if the le doesn’t exist.
except FileNotFoundError prints "Not found".
Output is Not found.
Question: Predict the output of the following code:
class Vehicle:

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.

You might also like