0% found this document useful (0 votes)
2 views24 pages

Python Answer Key

The document is a comprehensive question bank for Python programming, covering various topics such as data types, control structures, functions, and error handling. It includes detailed explanations, examples, and outputs for each question, designed to test and reinforce understanding of Python concepts. The total number of questions is 60, with each question worth 10 marks.

Uploaded by

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

Python Answer Key

The document is a comprehensive question bank for Python programming, covering various topics such as data types, control structures, functions, and error handling. It includes detailed explanations, examples, and outputs for each question, designed to test and reinforce understanding of Python concepts. The total number of questions is 60, with each question worth 10 marks.

Uploaded by

bhuvanivinoth816
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

Question Bank – Complete Answer Key


Total Questions: 60 | Each Question: 10 Marks

Question 1: Python Basics – Interpreter, Interactive Mode, Data Types


a) The Python Interpreter is a program that reads and executes Python code line by line.
It translates the high-level Python code into machine-understandable instructions at
runtime. It checks for syntax errors before execution and runs the code immediately
without the need for prior compilation into machine code.
b) Interactive Mode is a mode in Python where you can type Python statements one at a
time and the interpreter immediately executes each statement and displays the result.
It is accessed by typing 'python' in the command prompt/terminal. It is useful for
testing small code snippets.
c) Blanks 1) 10.5 belongs to float data type
2) True and False are boolean values
3) Strings are enclosed within single quotes (' ') or double quotes (" ")
d) Output Output: <class 'int'> <class 'float'>
Explanation: a = 10 is an integer; b = 5.0 is a float. type() returns the class/type of the
variable.

Question 2: Data Types – int, float, string, boolean


a) int: Whole numbers without decimal. Example: x = 10
float: Numbers with decimal point. Example: y = 3.14
Key difference: int uses less memory; float can represent fractional values. Python
automatically assigns the type based on the value.
b) Match 1. int → 25
2. float → 10.5
3. string → "Hello"
4. boolean → True
c) Output x / y → 5 / 2 = 2.5 (true division)
x // y → 5 // 2 = 2 (floor/integer division)
Output: 2.5 2
d) Yes, Python is case-sensitive. Example: variable 'Age' and 'age' are treated as two
different variables. Keywords like 'if', 'IF', 'If' are also different.

Question 3: Type Errors, Assignment vs Equality, bool, Mutable Types


a) Error: TypeError – cannot concatenate str and int.
a = "10" is a string; b = 5 is an integer.
Corrected Code:
a = int("10") # Convert string to int
b=5
print(a + b) # Output: 15
b) Error: SyntaxError – 'if x = 5' uses assignment operator (=) instead of comparison
(==).
Corrected Code:
x = 10
if x == 5:
print("Equal")
c) bool("") returns False. An empty string is a falsy value in Python. Any non-empty
string would return True.
d) Mutable data type: List
Example: l = [1, 2, 3]; l[0] = 10 → l becomes [10, 2, 3]
Lists allow modification of elements after creation, unlike immutable types such as
tuples or strings.

Question 4: Lists – Definition, Indexing, Operations


a) A List in Python is an ordered, mutable collection of items. It can store elements of
different data types. Lists are defined using square brackets [ ] and allow duplicate
elements. Example: l = [1, 'hello', 3.5, True]
b) Blanks 1) Lists are mutable (can be changed after creation)
2) Indexing starts from 0
3) len([1,2,3]) returns 3
c) To add an element to a list, use the append() method:
l = [1, 2, 3]
[Link](4)
print(l) # Output: [1, 2, 3, 4]
append() adds the element at the end of the list.
d) [ ] is an empty list. Its type is list.
type([]) → <class 'list'>

Question 5: Boolean Logic, bool(), Type Mismatch Error


a) Boolean logic is used with the modulus (%) operator to check divisibility:
n=8
if n % 2 == 0:
print('Even') # Output: Even
n=7
if n % 2 != 0:
print('Odd') # Output: Odd
% 2 == 0 returns True for even numbers; != 0 returns True for odd.
b) Output bool(0) → False (0 is falsy)
bool(1) → True (non-zero is truthy)
bool(-5) → True (any non-zero is truthy)
Output: False True True
c) Error: TypeError – unsupported operand type(s) for -: 'int' and 'str'
x = 5 is an integer; y = "5" is a string.
You cannot subtract a string from an integer.
Fix: y = int("5") then print(x - y) # Output: 0

Question 6: Values, Data Types, Match, List Error, String


a) Values are the actual data stored in a variable. Each value belongs to a data type that
determines what operations can be performed on it.
Common data types in Python:
- int: Whole numbers (e.g., 5)
- float: Decimal numbers (e.g., 3.14)
- str: Text (e.g., "Hello")
- bool: True or False
- list: Ordered collection (e.g., [1,2,3])
b) Match 1. True → boolean
2. 3.14 → float
3. [1,2] → list
4. "Hi" → string
c) Error Error: 'list' is a built-in function name being used as a variable.
list = [1,2,3] overrides the built-in list type.
Also, list(0) is not valid syntax for indexing – use list[0].
Fix: rename the variable, e.g., my_list = [1,2,3]; print(my_list[0]) # Output: 1
d) Example of a string: name = "Python"
A string is a sequence of characters enclosed in quotes. It is immutable – once
created, it cannot be changed.

Question 7: Variables and Expressions


a) A variable is a named location in memory used to store data. The value stored can
change during execution.
Example: x = 10 → x is a variable holding integer value 10.
b) An expression is a combination of values, variables, and operators that produces a
result.
Example: x + 5 is an expression. When x = 3, it evaluates to 8.
c) Blanks 1) A variable stores a value (data)
2) x = 5 + 3 is an example of an assignment statement with an expression
3) Variable names should not start with a digit (number)
d) Output x = 10
y = x + 5 → y = 15
print(y) → Output: 15

Question 8: Expression vs Statement, Match, Operators


a) Expression: A combination of values and operators that returns a value.
Example: x + y, 5 * 3
Statement: A complete instruction that Python executes.
Example: x = 5 (assignment statement), print(x)
Key difference: Expressions produce a value; statements perform an action.
b) Match 1. x = 5 → b. Statement
2. x + y → a. Expression
3. # comment → c. Comment
4. * → d. Operator
c) Blanks Expression produces a value and statement performs an action.
d) Answer Correct answer: c) *
* is an arithmetic operator (multiplication). x = 5 is a statement, x + y is an expression,
# comment is a comment.
Question 9: Operator Precedence
a) Operator precedence program:
result = 2 + 3 * 4 # Multiplication first
print(result) # Output: 14
result2 = (2 + 3) * 4 # Brackets first
print(result2) # Output: 20
Precedence order (high to low): () → ** → * / // % → + -
b) Output print(2 + 3 * 4)
Step 1: 3 * 4 = 12 (multiplication has higher precedence)
Step 2: 2 + 12 = 14
Output: 14
c) Blanks * has higher precedence than + and brackets have the highest priority.
d) Answer Correct answer: c) ()
Brackets (parentheses) are always evaluated first in Python.

Question 10: Comments in Python


a) # Program with comments explaining each step
x = 10 # Assign value 10 to variable x
y = x * 2 # Multiply x by 2 and store in y
z = y + 5 # Add 5 to y and store in z
print(z) # Display the final result
# Output: 25
b) Output x = 10
# x = x + 5 ← This line is a comment, Python ignores it
print(x)
Output: 10
The commented line does not affect the value of x.
c) Blanks Comments are used for documentation/explanation and they do not affect program
execution.
d) Answer Correct answer: b) comment
Python ignores everything after the # symbol on a line.

Question 11: Divisibility – % and == Operators


a) # Check divisibility by both 2 and 3
x = int(input("Enter a number: "))
if x % 2 == 0 and x % 3 == 0:
print(x, "is divisible by both 2 and 3")
else:
print(x, "is not divisible by both 2 and 3")
b) Output x=6
print(x % 2 == 0 and x % 3 == 0)
6 % 2 = 0 → True; 6 % 3 = 0 → True
True and True = True
Output: True
c) Blanks % gives the remainder and == checks equality.
d) Answer Correct answer: b) ==
== is the equality operator. = is assignment, != is not-equal, >= is greater-than-or-
equal.

Question 12: Error Correction – Missing Operand, Comparison Operators


a) Error Error in: print(x + y * )
SyntaxError: missing operand after *
Corrected Code:
x=5
y=2
print(x + y * 2) # or any valid number
Output: 9
b) Output print(5 + 2 * 3 > 10)
Step 1: 2 * 3 = 6
Step 2: 5 + 6 = 11
Step 3: 11 > 10 → True
Output: True
c) Blanks Comparison operators return boolean values and precedence decides the order of
evaluation.
d) Answer Correct answer: c) True
Boolean results are True or False. 7 is an integer, "7" is a string, x+2 is an
expression.

Question 13: if Statement – Syntax, Comparison Operators


a) Error Error: Missing colon (:) at end of if condition – SyntaxError.
Original: if x > 3
Corrected Code:
x=5
if x > 3:
print("Yes")
Output: Yes
b) Output x=2
if x == 2: → True
print("A") → prints A
Output: A
c) Blank if statement is used for conditional execution / decision making.
d) Answer Correct answer: b) ==
== is the comparison (equality) operator. = is assignment, + is arithmetic, % is
modulus.

Question 14: for Loop – range(), Iterations


a) # Print numbers from 1 to 5 using for loop
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
b) Output for i in range(3):
print(i)
range(3) generates: 0, 1, 2
Output:
0
1
2
c) Blank Loop is used to repeat a block of code multiple times.
d) Answer Correct answer: b) for
for loop is used when the number of iterations is known. while is used when the
condition is unknown in advance.

Question 15: while Loop – Indentation Error, break and continue


a) Error Error: IndentationError – print(i) and i += 1 are not indented inside the while block.
Corrected Code:
i=1
while i < 3:
print(i)
i += 1
Output:
1
2
b) Output for i in range(2):
if i == 1:
break
print(i)
i=0: condition 0==1 is False, prints 0
i=1: condition 1==1 is True, break exits loop
Output: 0
c) Blank The statement used to exit a loop is break.
d) Answer Correct answer: b) continue
continue skips the rest of the current iteration and goes to the next. break exits the
loop entirely.

Question 16: Functions – Parameters, return


a) # Function to return square of a number
def square(n):
return n * n

result = square(5)
print(result) # Output: 25
b) Output def fun(x):
return x + 2
print(fun(3))
fun(3) → 3 + 2 = 5
Output: 5
c) Blanks The input to a function is called a parameter (or argument) and a function that returns
a value is called a value-returning function (or non-void function).
d) Answer Correct answer: b) return
The return keyword is used to send a value back from a function to the caller.

Question 17: Even Numbers Using Loop


a) # Print even numbers from 1 to 10
for i in range(1, 11):
if i % 2 == 0:
print(i)
Output: 2, 4, 6, 8, 10
b) Output x=1
while x <= 3:
print(x)
x += 1
Output:
1
2
3
c) Blanks % operator is used to find the remainder and even number is checked using n % 2 ==
0.
d) Answer Correct answer: a) %2==0
A number is even if the remainder when divided by 2 equals 0.

Question 18: Modules – import Statement


a) # Syntax to import a module
import math # Full import
from math import sqrt # Specific import
import math as m # Import with alias

# Usage:
print([Link](16)) # Output: 4.0
print(sqrt(25)) # Output: 5.0
print([Link]) # Output: 3.14159...
b) Match 1. import math → full import
2. [Link](4) → use function
3. from math import sqrt → specific import
c) Blanks Module is a Python file (with .py extension) and it contains functions, variables, and
classes.
d) Answer Correct answer: b) import
import is the keyword used to include a module in the program.

Question 19: Recursion – Factorial


a) # Recursive function to find factorial
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive call

print(factorial(5)) # Output: 120


b) Output def fun(n):
if n == 1:
return 1
return n * fun(n-1)
print(fun(3))
fun(3) = 3 * fun(2) = 3 * 2 * fun(1) = 3 * 2 * 1 = 6
Output: 6
c) Blanks Recursion means a function calling itself and it must have a base case condition
(stopping condition).
d) Answer Correct answer: b) base case
A recursive function must have a base case to stop the recursion, otherwise it will
cause infinite recursion.

Question 20: Recursion – Missing Base Case, Stack


a) Error Error: Missing base case – leads to infinite recursion and RecursionError: maximum
recursion depth exceeded.
Corrected Code:
def fun(n):
if n == 0: # Base case added
return 1
return n * fun(n-1)
print(fun(3)) # Output: 6
b) Output def show(n):
if n == 0:
return
print(n)
show(n-1)
show(3)
Output:
3
2
1
c) Blanks Missing stopping condition causes infinite recursion (RecursionError) and recursion
uses stack memory.
d) Answer Correct answer: a) stack
Recursion uses the call stack. Each function call is pushed onto the stack and popped
when it returns.

Question 21: Strings – Indexing, Immutability


a) # Print each character in a string
s = "Python"
for ch in s:
print(ch)
Output:
P
y
t
h
o
n
b) Output s = "Hi"
print(s[0], s[1])
s[0] = 'H', s[1] = 'i'
Output: H i
c) Blanks String is a sequence of characters and indexing starts from 0.
d) Answer Correct answer: b) immutable
Strings are immutable in Python – you cannot change individual characters after
creation.

Question 22: List – Remove Duplicates, pop(), sort()


a) # Remove duplicates from a list
l = [1, 2, 2, 3, 1, 4]
l = list(set(l)) # Convert to set removes duplicates, then back to list
print(l) # Output: [1, 2, 3, 4] (order may vary)
b) Output l = [1,2,3]
[Link]() # Removes last element (3)
print(l)
Output: [1, 2]
c) Blanks pop() removes the last element (or element at given index) and list can store multiple
data types.
d) Answer Correct answer: b) sort()
[Link]() sorts the list in ascending order in-place. order(), arrange() do not exist; set()
converts to a set.

Question 23: String – Palindrome, count(), isalpha()


a) # Check whether a string is palindrome
s = input("Enter a string: ")
if s == s[::-1]:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
b) Output s = "abcabc"
print([Link]("a"))
Counting 'a' in 'abcabc': positions 0 and 3
Output: 2
c) Blanks count() returns the number of occurrences of a substring and strings cannot be
modified (they are immutable).
d) Answer Correct answer: b) isalpha()
isalpha() returns True if all characters in the string are alphabetic letters.

Question 24: Recursion – Countdown, Infinite Recursion


a) # Recursive function to print numbers from n to 1
def countdown(n):
if n == 0: # Base case
return
print(n)
countdown(n - 1)
countdown(5)
Output: 5, 4, 3, 2, 1
b) Output def fun(n):
if n == 0:
return
print(n)
fun(n-1)
fun(4)
Output:
4
3
2
1
c) Blanks Recursive function calls itself and stops when the base case condition is met.
d) Answer Correct answer: a) base case missing
Infinite recursion occurs when there is no base case or the base case is never
reached.

Question 25: List – Addition and Removal of Elements


a) l = [1, 2, 3]
# Adding elements
[Link](4) # Add at end
[Link](1, 10) # Insert at index 1
print(l) # [1, 10, 2, 3, 4]
# Removing elements
[Link](10) # Remove by value
print(l) # [1, 2, 3, 4]
b) Output l = [1,2,3]
l = l + [4,5] # Concatenation creates new list
print(l)
Output: [1, 2, 3, 4, 5]
c) Blanks + is used for concatenating (joining) lists and remove() deletes the first matching
element.
d) Answer Correct answer: b) append()
append() adds an element at the end of the list. insert() adds at a specific position.

Question 26: List – Slicing, Alternate Elements


a) # Print alternate elements from a list
l = [10, 20, 30, 40, 50]
print(l[::2]) # Step 2 – alternate elements
Output: [10, 30, 50]
b) Output l = [10,20,30,40,50]
print(l[1:4:2])
Slice from index 1 to 3 with step 2: elements at index 1(20) and 3(40)
Output: [20, 40]
c) Blanks Slicing uses the : (colon) operator and step value decides how many elements to
skip.
d) Answer Correct answer: a) l[::-1]
l[::-1] reverses the list using slicing with step -1.

Question 27: List – sort(), reverse(), count()


a) l = [3, 1, 4, 1, 5, 9, 2]
[Link]() # Sorts in ascending order
print(l) # [1, 1, 2, 3, 4, 5, 9]
[Link]() # Reverses the list
print(l) # [9, 5, 4, 3, 2, 1, 1]
b) Output l = [3,1,2]
[Link]() # Sorts in ascending order
print(l)
Output: [1, 2, 3]
c) Blanks sort() arranges list in ascending order and reverse() changes the order to the opposite
(reverses in-place).
d) Answer Correct answer: a) count()
count() counts the number of times an element appears in the list. find(), search(),
get() are not list methods.

Question 28: List – Iteration with for Loop


a) # Print all elements of list using loop
l = [10, 20, 30, 40, 50]
for element in l:
print(element)
Output:
10
20
30
40
50
b) Output l = [1,2,3]
for i in l:
print(i*2)
Output:
2
4
6
(Each element multiplied by 2)
c) Blanks Loop iterates over each element and variable i stores the current element in each
iteration.
d) Answer Correct answer: b) for
for loop is used to iterate over lists and other sequences. if is not a loop; def defines a
function.

Question 29: List – Modifying Elements (Mutability)


a) # Change an element in a list
l = [10, 20, 30]
l[1] = 99 # Change second element
print(l) # Output: [10, 99, 30]
Lists are mutable, so individual elements can be updated using their index.
b) Output l = [1,2,3]
l[1] = 10 # Replace element at index 1
print(l)
Output: [1, 10, 3]
c) Blanks List is a mutable type and elements can be modified (changed after creation).
d) Answer Correct answer: c) list
Lists are mutable. Strings, tuples, and int are immutable.

Question 30: List – Aliasing


a) # Aliasing of lists
l1 = [1, 2, 3]
l2 = l1 # l2 is an alias (same reference)
[Link](4)
print(l1) # Output: [1, 2, 3, 4]
print(l2) # Output: [1, 2, 3, 4]
# Both point to same object; use l2 = [Link]() to avoid this.
b) Output l1 = [1,2]
l2 = l1 # Aliasing – both refer to same list
[Link](3) # Modifies the shared object
print(l1)
Output: [1, 2, 3]
c) Blanks Aliasing means two variables refer to the same object and any change affects both
variables.
d) Answer Correct answer: c) same reference
Aliasing creates a shared reference – both variables point to the same list in memory.

Question 31: Tuples – Creation, Indexing, Immutability


a) # Create a tuple and print its elements
t = (10, 20, 30, 40)
for element in t:
print(element)
Output:
10
20
30
40
b) Output t = (1,2,3)
print(t[1])
t[1] is 2 (indexing starts from 0)
Output: 2
c) Blanks Tuple is an immutable type and elements are fixed (cannot be changed after
creation).
d) Answer Correct answer: b) immutable
Tuples are immutable – once created, their elements cannot be modified.

Question 32: Tuple Assignment – Variable Swapping


a) # Swap two variables using tuple assignment
a=5
b = 10
a, b = b, a # Tuple packing and unpacking
print(a, b) # Output: 10 5
b) Output a, b = 2, 3
a, b = b, a # Swap values
print(a, b)
Output: 3 2
c) Blanks Tuple assignment allows simultaneous swapping and no need of a temporary
variable.
d) Answer Correct answer: b) ()
Tuple packing uses parentheses (). x,y = 1,2 is tuple unpacking.

Question 33: Functions Returning Multiple Values via Tuples


a) # Function returning sum and product using tuple
def calc(a, b):
return a + b, a * b # Returns a tuple

s, p = calc(3, 4)
print("Sum:", s) # Output: Sum: 7
print("Product:", p) # Output: Product: 12
b) Output def fun():
return 2, 3
x, y = fun()
print(x + y)
fun() returns (2, 3); x=2, y=3; x+y=5
Output: 5
c) Blanks Function returns multiple values using a tuple and values are unpacked into individual
variables.
d) Answer Correct answer: b) tuple
When a function returns multiple values, Python automatically packs them into a
tuple.

Question 34: Dictionary – Add and Delete Elements


a) # Add and delete elements in a dictionary
d = {"name": "Alice", "age": 20}
d["city"] = "Delhi" # Add new key-value pair
print(d)
del d["age"] # Delete element
print(d)
# Or: [Link]("age")
b) Output d = {"x":10}
d["y"] = 20
print(len(d))
d now has keys 'x' and 'y'
Output: 2
c) Blanks len() gives the number of key-value pairs and new element is added using d[key] =
value.
d) Answer Correct answer: b) del and c) pop()
del d[key] and [Link](key) both delete a key. del is a statement; pop() is a method that
also returns the value.

Question 35: Dictionary – keys(), values(), items()


a) d = {"a": 1, "b": 2, "c": 3}
print("Keys:", list([Link]())) # ['a', 'b', 'c']
print("Values:", list([Link]())) # [1, 2, 3]
print("Items:", list([Link]())) # [('a',1), ('b',2), ('c',3)]
b) Output d = {"a":1, "b":2}
print(list([Link]()))
Output: ['a', 'b']
c) Blanks keys() returns all the keys in the dictionary and values() returns all the values.
d) Answer Correct answer: a) items()
items() returns key-value pairs as tuples.

Question 36: List Comprehension


a) # Filter even numbers using list comprehension
l = [x for x in range(1, 11) if x % 2 == 0]
print(l) # Output: [2, 4, 6, 8, 10]
b) Output l = [x for x in range(5) if x%2==0]
print(l)
range(5): 0,1,2,3,4; even numbers: 0,2,4
Output: [0, 2, 4]
c) Blanks Condition in comprehension is written after the if keyword and %2==0 checks if the
number is even.
d) Answer Correct answer: b) loop
List comprehension provides a concise way to replace for loops when creating lists.

Question 37: File Handling – Write and Read


a) # Create a file and write text
f = open("[Link]", "w") # Open in write mode
[Link]("Hello, Python!\n")
[Link]("File handling is easy.")
[Link]()

# Read and display


f = open("[Link]", "r")
print([Link]())
[Link]()
b) Output f = open("[Link]","w")
[Link]("Hello")
[Link]()
f = open("[Link]","r")
print([Link]())
Output: Hello
c) Blanks "w" mode is used for writing (creates or overwrites file) and read() is used to read the
entire file content.
d) Answer Correct answer: b) r
"r" (read) mode is used to open an existing file for reading.

Question 38: File Handling – Word Count


a) # Count number of words in a file
f = open("[Link]", "w")
[Link]("Hello World Python Programming")
[Link]()

f = open("[Link]", "r")
data = [Link]()
words = [Link]()
print("Word count:", len(words)) # Output: 4
[Link]()
b) Output f = open("[Link]","w"); [Link]("A B C"); [Link]()
f = open("[Link]")
data = [Link]()
print(len([Link]()))
"A B C".split() → ['A', 'B', 'C'] → length 3
Output: 3
c) Blanks split() separates the string into a list of words and len() counts the number of elements
in the list.
d) Answer Correct answer: a) read()
read() reads the entire file as a single string.

Question 39: Exception Handling – try-except


a) # Handle division error
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print(a / b)
except ZeroDivisionError:
print("Error: Cannot divide by zero")
b) Output try:
x = int("abc") # ValueError raised
except:
print("Error")
Output: Error
c) Blanks Exception occurs during runtime (execution) time and try is used to detect/catch the
error.
d) Answer Correct answer: b) except
The except block handles the error when an exception is raised in the try block.

Question 40: Format Operator – %s, %d, %f


a) name = "Alice"
marks = 95
percentage = 95.5
print("Name: %s" % name)
print("Marks: %d" % marks)
print("Percentage: %.2f" % percentage)
b) Output name = "Sam"
marks = 90
print("Name: %s Marks: %d" % (name, marks))
Output: Name: Sam Marks: 90
c) Blanks %s is used for string values and %d is used for integer values.
d) Answer Correct answer: c) %f
%f is the format specifier for floating-point (decimal) numbers.

Question 41: sys Module – Command Line Arguments


a) import sys
# [Link][0] = script name
# [Link][1], [2]... = arguments passed
print("Script name:", [Link][0])
for i in range(1, len([Link])):
print("Argument", i, ":", [Link][i])
# Run as: python [Link] arg1 arg2
b) Output import sys
print([Link][0])
Output: The name of the current script file (e.g., [Link])
c) Blanks [Link] stores command line arguments as a list and index starts from 0 (argv[0] is
the script name).
d) Answer Correct answer: a) sys
The sys module provides access to command line arguments via [Link].

Question 42: NumPy – Array Creation


a) import numpy as np

# Create a NumPy array


a = [Link]([10, 20, 30, 40, 50])
print("Array:", a)
print("Shape:", [Link]) # (5,)
print("Data type:", [Link]) # int64
b) Output import numpy as np
a = [Link]([1,2,3])
print([Link])
ndim gives the number of dimensions
Output: 1 (it is a 1D array)
c) Blanks ndim gives the number of dimensions and NumPy array is a multi-dimensional
structure (supports 1D, 2D, etc.).
d) Answer Correct answer: a) array()
[Link]() is used to create a NumPy array.

Question 43: Pandas – Series


a) import pandas as pd
# Create a Pandas Series
s = [Link]([100, 200, 300], index=['a', 'b', 'c'])
print(s)
print(s['b']) # Access by label → 200
b) Output import pandas as pd
s = [Link]([10,20,30])
print(s[1])
Index 1 → 20
Output: 20
c) Blanks Series is a one-dimensional structure and stores homogeneous (same type) data with
labels.
d) Answer Correct answer: b) data analysis
Pandas is a Python library used for data analysis and manipulation.

Question 44: Pandas – DataFrame


a) import pandas as pd

# Create a DataFrame with two columns


data = {"Name": ["Alice", "Bob"], "Age": [20, 25]}
df = [Link](data)
print(df)
b) Output import pandas as pd
d = {"A":[1,2], "B":[3,4]}
df = [Link](d)
print(df["A"])
Output:
0 1
1 2
Name: A, dtype: int64
c) Blanks DataFrame is a two-dimensional structure and columns are labeled (named) data
series.
d) Answer Correct answer: b) table
DataFrame is like a table (rows and columns), similar to a spreadsheet.

Question 45: Pandas – Adding Columns


a) import pandas as pd
df = [Link]({"Price": [100, 200, 300]})
df["Tax"] = df["Price"] * 0.1 # Add Tax column
df["Total"] = df["Price"] + df["Tax"] # Add Total column
print(df)
b) Output import pandas as pd
df = [Link]({"A":[1,2]})
df["B"] = df["A"] * 2
print(df)
Output:
A B
0 1 2
1 2 4
c) Blanks New column is added using df["column_name"] = value and operations are column-
based (applied element-wise).
d) Answer Correct answer: b) df["A"]
Columns are selected using df["column_name"] with square brackets and the column
name as a string.

Question 46: Pandas – Filtering Rows


a) import pandas as pd
df = [Link]({"Marks": [45, 70, 80, 55, 90]})
# Select rows where Marks > 60
result = df[df["Marks"] > 60]
print(result)
b) Output import pandas as pd
df = [Link]({"A":[1,2,3]})
print(df[df["A"] > 1])
Output:
A
1 2
2 3
(Rows where A > 1)
c) Blanks Condition filtering returns only the matching rows and uses comparison operators (>,
<, ==, etc.).
d) Answer Correct answer: a) df[]
df[condition] filters rows based on a boolean condition.

Question 47: Pandas – Aggregate Functions (mean, max)


a) import pandas as pd
df = [Link]({"Marks": [60, 70, 80, 90]})
print("Mean:", df["Marks"].mean()) # 75.0
print("Max:", df["Marks"].max()) # 90
print("Min:", df["Marks"].min()) # 60
print("Sum:", df["Marks"].sum()) # 300
b) Output import pandas as pd
df = [Link]({"A":[2,4,6]})
print(df["A"].mean())
mean = (2+4+6)/3 = 12/3 = 4.0
Output: 4.0
c) Blanks mean() gives the average value and sum() gives the total sum of all values.
d) Answer Correct answer: a) max()
max() returns the maximum value in the column. avg() does not exist in Pandas; use
mean().

Question 48: Matplotlib – Line Plot


a) import [Link] as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
[Link](x, y)
[Link]("Line Plot")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
b) Output import [Link] as plt
x = [1,2,3]; y = [2,4,6]
[Link](x,y)
[Link]()
Output: Displays a line graph with points (1,2), (2,4), (3,6) connected by a line.
c) Blanks plot() is used for a line graph and show() is used to display the graph on screen.
d) Answer Correct answer: b) plotting
Matplotlib is a Python library used for data visualization and plotting graphs.

Question 49: Types of Errors – Syntax Error


a) # Program with syntax error
x = 10
if x > 5 # Missing colon – SyntaxError
print("Greater")

# Corrected version:
x = 10
if x > 5:
print("Greater")
b) Error if 5 > 3 # Missing colon
Type print("Yes")
Type of Error: SyntaxError
Reason: The if statement is missing the colon (:) at the end, which is required in
Python syntax.
c) Blanks Syntax error occurs at compile/parse time and it is due to a grammar/structure
mistake in the code.
d) Answer Correct answer: a) interpreter
In Python, the interpreter detects syntax errors before executing the program.

Question 50: Types of Errors – Runtime Error


a) # Program that produces runtime error
try:
x = 10
y=0
result = x / y # ZeroDivisionError
print(result)
except ZeroDivisionError as e:
print("Runtime Error:", e)
b) Error x = 10
y=0
print(x / y)
Error: ZeroDivisionError: division by zero
This is a runtime error – occurs during execution, not during parsing.
c) Blanks Runtime error occurs during program execution and division by zero gives
ZeroDivisionError.
d) Answer Correct answer: c) zero division
ZeroDivisionError is a runtime error that occurs when dividing by zero.

Question 51: Importance of Exception Handling


a) # Without exception handling
print(10 / 0) # ZeroDivisionError – program crashes
print("Done") # This line never executes
# Problem: When an unhandled exception occurs, the program terminates abruptly
and no further code is executed.
b) Output print(10/0)
print("Done")
Output:
ZeroDivisionError: division by zero
("Done" is never printed because program crashes at line 1)
c) Blanks Exception handling prevents program crashes and allows graceful/continued
execution.
d) Answer Correct answer: c) program stability
Exception handling improves program stability by gracefully managing errors.

Question 52: try-except-finally


a) # try-except to handle division error
try:
a = int(input("Numerator: "))
b = int(input("Denominator: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")
b) Output try:
print(5/0) # ZeroDivisionError raised
except:
print("Handled") # except block runs
Output: Handled
c) Blanks try block contains the risky/error-prone code and except handles the exception if one
is raised.
d) Answer Correct answer: c) finally
The finally block always runs whether or not an exception occurred – used for
cleanup operations.

Question 53: ValueError, IndexError – Built-in Exceptions


a) # Handle ValueError
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a valid integer.")
b) int("abc")
Exception Exception: ValueError
Reason: int() cannot convert the non-numeric string "abc" to an integer.
c) Blanks ValueError occurs for an invalid type conversion and IndexError occurs for an out-of-
range index.
d) Answer Correct answer: b) ValueError
ValueError is a built-in Python exception. MyError, UserError, and CustomError are
user-defined names.

Question 54: Multiple Exceptions


a) try:
x = int(input("Enter number: "))
y = int(input("Enter divisor: "))
print(x / y)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
b) Output try:
x = int("a") # ValueError raised here
y = 10/0 # This line is never reached
except ValueError:
print("Value Error") # This block executes
except ZeroDivisionError:
print("Zero Error")
Output: Value Error
c) Blanks Only the first matching exception block executes and order of except blocks is
important (specific before general).
d) Answer Correct answer: c) multiple except
Multiple except blocks handle different types of exceptions.

Question 55: User-Defined Exceptions


a) # Create and raise a user-defined exception
class AgeError(Exception):
pass

try:
age = int(input("Enter age: "))
if age < 0:
raise AgeError("Age cannot be negative")
print("Age:", age)
except AgeError as e:
print("Custom Error:", e)
b) Output class MyError(Exception):
pass
try:
raise MyError # Manually raise exception
except MyError:
print("Custom Error")
Output: Custom Error
c) Blanks User-defined exception is created using class (inheriting from Exception) and raised
using the raise keyword.
d) Answer Correct answer: b) raise
raise is used to manually trigger an exception in Python.

Question 56: math Module


a) import math

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


sqrt_val = [Link](num)
print("Square Root:", sqrt_val)
print("Floor:", [Link](sqrt_val))
print("Ceil:", [Link](sqrt_val))
b) Output import math
print([Link](4.2))
ceil() returns the smallest integer >= 4.2 → 5
Output: 5
c) Blanks math is a standard library (built-in module) and ceil() returns the ceiling value
(smallest integer greater than or equal to the number).
d) Answer Correct answer: c) math
math is a Python standard (built-in) library. numpy, pandas, and matplotlib are third-
party libraries.

Question 57: os Module – File System Operations


a) import os

# Display current working directory


cwd = [Link]()
print("Current Directory:", cwd)

# List files in directory


files = [Link](".")
print("Files:", files)
b) Output import os
print([Link])
Output: 'nt' (on Windows) or 'posix' (on Linux/Mac)
[Link] returns the name of the operating system.
c) Blanks os module is used for operating system-related operations and [Link] gives the
name of the OS platform.
d) Answer Correct answer: b) [Link]()
[Link](path) changes the current working directory. [Link]() creates a directory.

Question 58: CSV Module – Reading CSV Files


a) import csv

# Create and read CSV file


with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["Name", "Marks"])
[Link](["Alice", 90])
[Link](["Bob", 85])

with open("[Link]", "r") as f:


reader = [Link](f)
for row in reader:
print(row)
b) Output import csv
f = open("[Link]")
r = [Link](f)
for row in r:
print(row)
Output: Each row printed as a list, e.g., ['Name', 'Marks'] for header row.
c) Blanks CSV stands for Comma-Separated Values and reader() reads data as a list for each
row.
d) Answer Correct answer: b) comma
CSV files use comma (,) as the delimiter to separate values in each row.

Question 59: json Module – loads() and dump()


a) import json

# Read JSON data


json_str = '{"name": "Alice", "age": 20}'
data = [Link](json_str) # Convert JSON string to dict
print(data["name"]) # Output: Alice

# Write JSON
with open("[Link]", "w") as f:
[Link](data, f) # Write dict as JSON file
b) Output import json
data = '{"a":1}'
d = [Link](data)
print(d["a"])
[Link]() converts JSON string to Python dict; d["a"] = 1
Output: 1
c) Blanks json stores data in key-value (dictionary/object) format and loads() converts a JSON
string to a Python dictionary.
d) Answer Correct answer: b) dump()
[Link]() writes a Python dictionary to a file as JSON. [Link]() converts to a
JSON string.

Question 60: Marks Validation – Comparison Operators


a) # Check whether marks are between 0 and 100
marks = int(input("Enter marks: "))
if 0 <= marks <= 100:
print("Valid marks")
else:
print("Invalid marks")
b) Output marks = 105
if 0 <= marks <= 100:
print("Valid")
else:
print("Invalid")
105 is not in range [0, 100]
Output: Invalid
c) Blanks Condition uses the <= (less than or equal) operator and valid range is 0 to 100
(inclusive).
d) Answer Correct answer: c) <=
<= (less than or equal to) is used to check if marks fall within the valid range.

You might also like