0% found this document useful (0 votes)
33 views85 pages

Unit 1

The document outlines the concept of problem-solving in programming, emphasizing the importance of understanding the problem, defining inputs and outputs, and using structured approaches like algorithms and flowcharts. It covers various aspects such as program design, modular programming, and the significance of clarity in algorithms. Additionally, it provides insights into Python's history, features, and syntax, including the differences between Python versions.

Uploaded by

singhalaprajita0
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)
33 views85 pages

Unit 1

The document outlines the concept of problem-solving in programming, emphasizing the importance of understanding the problem, defining inputs and outputs, and using structured approaches like algorithms and flowcharts. It covers various aspects such as program design, modular programming, and the significance of clarity in algorithms. Additionally, it provides insights into Python's history, features, and syntax, including the differences between Python versions.

Uploaded by

singhalaprajita0
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/ 85

Concept of Problem Solving

1. What is the first step in problem-solving?


a) Writing the program
b) Understanding the problem
c) Debugging the program
d) Testing the solution

Answer: b) Understanding the problem

2. Which of the following is NOT a characteristic of a good problem-solving approach?


a) Efficiency
b) Complexity
c) Clarity
d) Accuracy

Answer: b) Complexity

3. What does "algorithm" mean in programming?


a) A programming language
b) A graphical representation of a problem
c) A step-by-step procedure for solving a problem
d) An error in the program

Answer: c) A step-by-step procedure for solving a problem

4. A problem that cannot be broken into smaller parts is called:


a) Modular problem
b) Atomic problem
c) Complex problem
d) Simple problem

Answer: b) Atomic problem

5. Which tool is commonly used for planning solutions in problem-solving?


a) Compiler
b) Debugger
c) Flowchart
d) Editor

Answer: c) Flowchart

6. Which of the following is a systematic approach to solving problems?


a) Guessing the solution
b) Following a random sequence
c) Using a structured process like algorithms or flowcharts
d) Ignoring problem constraints

Answer: c) Using a structured process like algorithms or flowcharts

7. Which of these is an example of a heuristic approach to problem-solving?


a) Finding the shortest path using Dijkstra’s algorithm
b) Trial and error to identify a solution
c) Using a fixed formula
d) Writing code directly without a plan

Answer: b) Trial and error to identify a solution

8. What is a 'well-defined problem'?


a) A problem with unclear goals
b) A problem that has precise input, process, and output requirements
c) A problem that requires guessing
d) A problem without constraints

Answer: b) A problem that has precise input, process, and output requirements

9. In problem-solving, constraints refer to:


a) Random inputs to the problem
b) Rules or conditions that must be followed
c) Steps to debug the code
d) The programming language used

Answer: b) Rules or conditions that must be followed

10. What is the final step in the problem-solving process?


a) Testing the solution
b) Defining the problem
c) Designing the algorithm
d) Writing pseudocode

Answer: a) Testing the solution

11. A clear problem definition ensures:


a) More errors in the solution
b) Faster coding without understanding the problem
c) Better communication between stakeholders and developers
d) Reducing the time spent on design

Answer: c) Better communication between stakeholders and developers


12. Which of the following is an example of a poorly defined problem?
a) Finding the sum of two given numbers
b) Writing a program to manage inventory without specifying inputs or outputs
c) Designing a calculator with defined functionality
d) Writing a program to sort a list

Answer: b) Writing a program to manage inventory without specifying inputs or outputs

13. Why is it important to identify inputs in problem definition?


a) To reduce execution time
b) To understand what data is required for processing
c) To identify the programming language
d) To design better hardware

Answer: b) To understand what data is required for processing

14. When defining a problem, understanding the 'output' means:


a) Knowing what the program should produce as a result
b) Deciding on the hardware for the program
c) Debugging the code
d) Ignoring the constraints

Answer: a) Knowing what the program should produce as a result

15. Which of the following is an essential part of a problem definition?


a) Input data, processing steps, and desired output
b) Only the input data
c) The choice of programming language
d) Ignoring constraints

Answer: a) Input data, processing steps, and desired output

Problem Definition

16. What is problem definition in program planning?


a) Writing code
b) Documenting the steps for solving the problem
c) Clearly defining the problem's inputs, outputs, and constraints
d) Testing the program

Answer: c) Clearly defining the problem's inputs, outputs, and constraints

17. Which of these is NOT part of problem definition?


a) Input
b) Output
c) Memory location
d) Constraints

Answer: c) Memory location

18. What is the purpose of defining a problem clearly?


a) To avoid debugging
b) To minimize coding time
c) To ensure that the program solves the intended problem
d) To create flowcharts

Answer: c) To ensure that the program solves the intended problem

19. In problem-solving, identifying assumptions is important because:


a) It simplifies coding
b) It reduces errors
c) It clarifies limitations of the problem
d) It speeds up the execution

Answer: c) It clarifies limitations of the problem

20. Which element is part of a well-defined problem?


a) Undefined inputs
b) Clear objectives
c) Random constraints
d) Ambiguous results

Answer: b) Clear objectives

Program Design

21. Program design involves which of the following steps?


a) Execution
b) Implementation
c) Planning the solution and writing an algorithm
d) Debugging

Answer: c) Planning the solution and writing an algorithm

22. Which of these is a common design tool?


a) Compiler
b) Flowchart
c) Assembler
d) Editor
Answer: b) Flowchart

23. What is pseudocode?


a) A programming language
b) A way to describe algorithms using natural language and symbols
c) A graphical representation of a program
d) A debugging tool

Answer: b) A way to describe algorithms using natural language and symbols

24. Which of the following is NOT a characteristic of a good program design?


a) Scalability
b) Simplicity
c) Efficiency
d) Redundancy

Answer: d) Redundancy

25. Which phase comes after program design in the software development life cycle?
a) Problem definition
b) Testing
c) Coding
d) Debugging

Answer: c) Coding

26. Which of these is the first step in program design?


a) Writing code
b) Understanding the problem and defining objectives
c) Testing the program
d) Debugging the solution

Answer: b) Understanding the problem and defining objectives

27. What is the purpose of using pseudocode in program design?


a) To write executable code
b) To document the program
c) To plan and describe the logic of the program in simple terms
d) To define inputs

Answer: c) To plan and describe the logic of the program in simple terms

28. Modular programming involves dividing a problem into:


a) Irregular parts
b) Smaller, independent sub-problems or modules
c) Complex loops
d) Debugging tools

Answer: b) Smaller, independent sub-problems or modules

29. What is the primary goal of program design?


a) To write efficient and readable code
b) To skip problem analysis
c) To write only complex programs
d) To avoid errors during testing

Answer: a) To write efficient and readable code

30. A top-down design approach:


a) Starts with the details and builds up to the main problem
b) Focuses on solving one big problem at once
c) Breaks a problem into smaller, more manageable parts
d) Avoids planning and starts coding

Answer: c) Breaks a problem into smaller, more manageable parts

Flowcharts

31. What shape is used to represent a decision in a flowchart?


a) Rectangle
b) Oval
c) Diamond
d) Circle

Answer: c) Diamond

32. Which shape in a flowchart represents a process or action?


a) Rectangle
b) Oval
c) Parallelogram
d) Diamond

Answer: a) Rectangle

33. What does an arrow indicate in a flowchart?


a) A calculation
b) A connection between steps
c) An error
d) A condition

Answer: b) A connection between steps


34. Which of these best describes the use of flowcharts?
a) They execute the program
b) They visually represent the steps in a process
c) They debug code
d) They generate pseudocode

Answer: b) They visually represent the steps in a process

35. Why are flowcharts used in program planning?


a) To avoid errors
b) To visually organize the sequence of operations
c) To write code efficiently
d) To reduce programming time

Answer: b) To visually organize the sequence of operations

Algorithms

36. What is a key property of a good algorithm?


a) Ambiguity
b) Infinite loops
c) Clarity
d) Redundancy

Answer: c) Clarity

37. Which of the following is NOT an algorithm design technique?


a) Divide and conquer
b) Debugging
c) Dynamic programming
d) Greedy approach

Answer: b) Debugging

38. An algorithm must always have:


a) A single solution
b) A finite number of steps
c) A complex structure
d) Multiple inputs

Answer: b) A finite number of steps

39. What is the purpose of dry running an algorithm?


a) To check for syntax errors
b) To manually trace its steps and verify its logic
c) To execute the program
d) To debug code

Answer: b) To manually trace its steps and verify its logic

40. Which is NOT a part of an algorithm?


a) Input
b) Process
c) Output
d) Compilation

Answer: d) Compilation

Miscellaneous

41. What does modular programming involve?


a) Writing all code in one function
b) Dividing the program into small, manageable parts
c) Avoiding functions
d) Ignoring flowcharts

Answer: b) Dividing the program into small, manageable parts

42. What is the benefit of using structured programming?


a) Makes programs complex
b) Simplifies debugging and maintenance
c) Eliminates the need for testing
d) Improves execution speed

Answer: b) Simplifies debugging and maintenance

43. In top-down design, the problem is divided into:


a) Simple inputs
b) Logical errors
c) Smaller, manageable sub-problems
d) Complex loops

Answer: c) Smaller, manageable sub-problems

44. What is the primary goal of problem-solving in programming?


a) Writing the code
b) Finding the fastest algorithm
c) Delivering a solution that meets the requirements
d) Compiling the program

Answer: c) Delivering a solution that meets the requirements

45. Debugging is the process of:


a) Writing algorithms
b) Finding and fixing errors in the code
c) Testing program efficiency
d) Planning program design

Answer: b) Finding and fixing errors in the code

Python History and Features

42. Who developed Python programming language?


a) James Gosling
b) Guido van Rossum
c) Dennis Ritchie
d) Bjarne Stroustrup

Answer: b) Guido van Rossum

43. In which year was Python developed?


a) 1989
b) 1991
c) 1995
d) 2000

Answer: b) 1991

44. Python was inspired by which programming language?


a) ABC
b) Java
c) C++
d) Perl

Answer: a) ABC

45. What does Python emphasize?


a) Code readability and simplicity
b) Execution speed
c) Complex syntax
d) Strict typing

Answer: a) Code readability and simplicity


46. Which of the following is NOT a feature of Python?
a) Interpreted language
b) Easy to learn
c) Platform dependent
d) Open source

Answer: c) Platform dependent

47. What is the meaning of “Python” in the context of the language's name?
a) Named after the Python snake
b) Named after Monty Python comedy group
c) Acronym for a technical term
d) Randomly chosen

Answer: b) Named after Monty Python comedy group

48. What is the file extension of Python scripts?


a) .java
b) .py
c) .pl
d) .exe

Answer: b) .py

49. What was the first version of Python released?


a) Python 1.0
b) Python 2.0
c) Python 3.0
d) Python 0.9.0

Answer: d) Python 0.9.0

50. Which Python version discontinued support in 2020?


a) Python 3.7
b) Python 2.7
c) Python 3.0
d) Python 1.5

Answer: b) Python 2.7

51. Which organization currently manages Python?


a) Python Software Foundation
b) Microsoft
c) Oracle
d) Google
Answer: a) Python Software Foundation

Python Versions

52. What major change was introduced in Python 3.x compared to Python 2.x?
a) Removal of print as a statement
b) Inclusion of type hints
c) New syntax for loops
d) Faster execution

Answer: a) Removal of print as a statement

53. What is the latest Python version (as of 2025)?


a) Python 3.9
b) Python 3.10
c) Python 3.11
d) Python 3.12

Answer: d) Python 3.12

54. When was Python 3.x released?


a) 2000
b) 2005
c) 2008
d) 2010

Answer: c) 2008

55. What feature was introduced in Python 3.6?


a) F-strings for formatted string literals
b) Print as a function
c) List comprehensions
d) Dictionaries

Answer: a) F-strings for formatted string literals

56. Which of the following is deprecated in Python 3.x?


a) Raw_input()
b) Input()
c) Open()
d) Len()

Answer: a) Raw_input()
Python Basics

57. What type of language is Python?


a) Compiled
b) Interpreted
c) Both compiled and interpreted
d) None of the above

Answer: b) Interpreted

58. How do you execute a Python script?


a) python script.py
b) execute script.py
c) run script.py
d) start script.py

Answer: a) python script.py

59. Which of the following is a valid variable name in Python?


a) 123var
b) _var123
c) var-123
d) var 123

Answer: b) _var123

60. Which keyword is used to define a function in Python?


a) fun
b) def
c) func
d) define

Answer: b) def

61. Which of these data types is immutable in Python?


a) List
b) Dictionary
c) String
d) Set

Answer: c) String
The print Statement

62. What is the correct syntax for using the print function in Python 3?
a) print "Hello"
b) print("Hello")
c) echo "Hello"
d) Print("Hello")

Answer: b) print("Hello")

63. What does the sep parameter in print do?


a) Separates lines of text
b) Specifies the separator between arguments
c) Adds a newline
d) Formats strings

Answer: b) Specifies the separator between arguments

64. What is the default value of the end parameter in print?


a) A space
b) A tab
c) A newline (\n)
d) None

Answer: c) A newline (\n)

65. How can you print without a newline at the end?


a) Use end=" " in the print statement
b) Use sep=""
c) Use newline=False
d) Use no_newline=True

Answer: a) Use end=" " in the print statement

66. What is the output of print("A", "B", sep="-")?


a) A B
b) A-B
c) A B-
d) -A-B

Answer: b) A-B

Error Handling with print


67. What happens if you miss parentheses in a print statement in Python 3?
a) It executes normally
b) It raises a SyntaxError
c) It raises a NameError
d) It converts to Python 2 syntax

Answer: b) It raises a SyntaxError

68. What is the output of print("Hello", end="")?


a) Hello
b) Hello\n
c) Hello None
d) None

Answer: a) Hello

69. What is the purpose of file parameter in print?


a) Directs output to a specified file or stream
b) Reads input from a file
c) Appends data to a string
d) Closes the file

Answer: a) Directs output to a specified file or stream

70. Which of these results in a TypeError for the print function?


a) print(1, 2, 3)
b) print("Hello", end=123)
c) print("Hello" + 123)
d) print()

Answer: c) print("Hello" + 123)

71. What is the output of print("The value is", 5, sep=":")?


a) The value is 5
b) The value:5
c) The:value:is:5
d) The:value:is 5

Answer: b) The value:5

Miscellaneous

72. What function is used for formatted string output?


a) printf()
b) format()
c) write()
d) append()

Answer: b) format()

73. Which is used to comment a single line in Python?


a) //
b) /* */
c) #
d) <!-- -->

Answer: c) #

74. What is the output of print(len("Python"))?


a) 5
b) 6
c) 7
d) Error

Answer: b) 6

75. What is the output of print("Hello " * 3)?


a) HelloHelloHello
b) Hello 3
c) Hello Hello Hello
d) Error

Answer: c) Hello Hello Hello

76. What is the output of print(10/3)?


a) 3
b) 3.0
c) 3.33...
d) Error

Answer: c) 3.33...

77. Which tool is commonly used for breaking down complex problems?
a) Editor
b) Debugger
c) Flowchart
d) Compiler

Answer: c) Flowchart
78. Which of the following is an iterative process in problem-solving?
a) Debugging
b) Refining the algorithm and design after testing
c) Choosing a programming language
d) Writing documentation

Answer: b) Refining the algorithm and design after testing

79. The role of abstraction in problem-solving is to:


a) Eliminate errors in programming
b) Focus on the main problem while ignoring unnecessary details
c) Make the problem more complex
d) Avoid modularity

Answer: b) Focus on the main problem while ignoring unnecessary details

80. What is the role of testing in problem-solving?


a) To debug only minor errors
b) To validate the correctness and performance of the solution
c) To rewrite the problem definition
d) To replace program design

Answer: b) To validate the correctness and performance of the solution

81. Which is NOT an objective of program design?


a) Simplicity
b) Scalability
c) Ambiguity
d) Efficiency

Answer: c) Ambiguity

Multiple Choice Questions (MCQs) on Debugging in Python

82. What is debugging in Python?

A) Writing new code from scratch


B) Fixing errors in the code
C) Running the code without errors
D) Converting Python code to another language

Answer: B) Fixing errors in the code


83. Which of the following tools is commonly used for debugging in Python?

A) PIP
B) PyCharm Debugger
C) Python Debugger (pdb)
D) Both B and C

Answer: D) Both B and C

84. What is the default command to start debugging in Python using pdb?

A) import debug
B) import pdb; pdb.set_trace()
C) debug.start()
D) python debug.py

Answer: B) import pdb; pdb.set_trace()

85. What type of errors does debugging primarily help to fix?

A) Logical errors
B) Syntax errors
C) Runtime errors
D) All of the above

Answer: D) All of the above

86. Which Python statement is used to handle exceptions while debugging?

A) if-else
B) try-except
C) switch-case
D) for-loop

Answer: B) try-except

87. What does the pdb command n (next) do during debugging?

A) Steps into the function call


B) Executes the next line of code
C) Prints the next line of code
D) Terminates the debugging session
Answer: B) Executes the next line of code

88. What will happen if you use assert in Python debugging?

A) It will throw an exception if the condition is False


B) It will always execute without error
C) It will print debugging messages
D) It will log errors in a file

Answer: A) It will throw an exception if the condition is False

89. What is the main advantage of using a debugger instead of print statements for
debugging?

A) Debuggers execute faster


B) Debuggers allow step-by-step execution
C) Debuggers can only detect syntax errors
D) Debuggers remove errors automatically

Answer: B) Debuggers allow step-by-step execution

90. Which of the following can be used to log errors while debugging?

A) print()
B) logging module
C) sys.exit()
D) os.log()

Answer: B) logging module

91. How can you ignore exceptions while debugging in Python?

A) Use pass in try-except block


B) Use break in if-else block
C) Use continue in a loop
D) Use return in a function

Answer: A) Use pass in try-except block

Multiple Choice Questions (MCQs) on Syntax Errors in Python


92. What is a syntax error in Python?

A) An error due to incorrect logic


B) An error due to incorrect grammar of the language
C) An error that occurs only at runtime
D) An error that cannot be detected by the interpreter

Answer: B) An error due to incorrect grammar of the language

93. When do syntax errors occur in Python?

A) During program execution


B) During program compilation
C) Before the program runs
D) After program termination

Answer: C) Before the program runs

94. . What will happen if there is a syntax error in the Python code?

A) The program will execute with incorrect output


B) The program will run but give warnings
C) The program will not execute at all
D) The program will automatically fix the error

Answer: C) The program will not execute at all

95. What does Python display when it encounters a syntax error?

A) Warning message
B) Debugging message
C) SyntaxError message
D) Logical error message

Answer: C) SyntaxError message

96. Which of the following will result in a syntax error?

A) print("Hello World")
B) if x == 5: (without indentation)
C) def func(): return 5
D) x = 5 + 3

Answer: B) if x == 5: (without indentation)

97. What is the cause of the syntax error in the following statement?

print "Hello"

A) Missing parentheses
B) Incorrect indentation
C) Mismatched quotation marks
D) Wrong function name

Answer: A) Missing parentheses

98. What is wrong with this code?

if 5 > 3
print("Hello")

A) Incorrect indentation
B) Missing colon (:) after if
C) Missing parentheses in print
D) if should be IF

Answer: B) Missing colon (:) after if

99. Which of the following is a valid Python statement?

A) for i in range(5) print(i)


B) if x = 5:
C) while True: pass
D) def func: return 5

Answer: C) while True: pass

100. What is the cause of the syntax error in the following code?
def greet(name)
print("Hello", name)
A) Missing parentheses in print()
B) Missing colon : in function definition
C) Missing return statement
D) Incorrect function name

Answer: B) Missing colon : in function definition

101. Which of the following statements is incorrect and will cause a syntax error?

A) x = 5
B) if x == 5 print("Hello")
C) for i in range(5): print(i)
D) while True: break

Answer: B) if x == 5 print("Hello")

102. What will cause a syntax error in Python?

A) Using an undefined variable


B) Using incorrect indentation
C) Dividing by zero
D) Using a very large number

Answer: B) Using incorrect indentation

103. Identify the syntax error in this statement:

if (x > 10) then:


print("x is greater")

A) then is not required in Python


B) Missing parentheses in print()
C) Incorrect indentation
D) if should be uppercase

Answer: A) then is not required in Python


104. Which of the following will NOT cause a syntax error?

A) x = 5 +
B) if x == 5:
C) print("Hello"
D) for i in range(5) print(i)

Answer: B) if x == 5:

105. What is wrong with this loop?


for i in range(5)
print(i)

A) Missing colon : after range(5)


B) print(i) should be inside parentheses
C) for should be capitalized
D) i should be initialized

Answer: A) Missing colon : after range(5)

106. How can you correct the syntax error in this function definition?

def add(a, b)
return a + b

A) Add a colon : after (a, b)


B) Use return a + b inside an if block
C) Remove the parentheses
D) Add an else statement

Answer: A) Add a colon : after (a, b)

107. Which of the following statements will cause a syntax error?

A) print("Hello World")
B) if x == 10 print("x is 10")
C) while True: pass
D) x = 100

Answer: B) if x == 10 print("x is 10")


108. What is the issue with this function call?

print "Hello, World!"

A) Missing parentheses
B) Incorrect function name
C) print should be capitalized
D) Hello, World! should be in single quotes

Answer: A) Missing parentheses

109. What is wrong with this assignment statement?

if x = 5:
print("x is 5")

A) = should be ==
B) print should be in uppercase
C) if should be capitalized
D) The colon : should be removed

Answer: A) = should be ==

110. What will happen if you use mismatched parentheses in an expression?

print("Hello"

A) The program will run normally


B) A SyntaxError will be raised
C) The program will ignore the extra parenthesis
D) The output will be Hello

Answer: B) A SyntaxError will be raised

111. What will cause a syntax error in Python?

A) Using print with parentheses


B) Declaring a variable with a number first (e.g., 1var = 10)
C) Using if-else statements
D) Using while loops

Answer: B) Declaring a variable with a number first (e.g., 1var = 10)

Multiple Choice Questions (MCQs) on Runtime Errors in Python

112. What is a runtime error in Python?

A) An error that occurs before the program runs


B) An error that occurs during the execution of the program
C) An error due to incorrect indentation
D) An error that prevents compilation

Answer: B) An error that occurs during the execution of the program

113. Which of the following is an example of a runtime error?

A) SyntaxError
B) ZeroDivisionError
C) IndentationError
D) TypeError

Answer: B) ZeroDivisionError

114. What will happen when the following code runs?

x = 10 / 0

A) It will execute successfully


B) It will throw a ZeroDivisionError
C) It will return None
D) It will print 0

Answer: B) It will throw a ZeroDivisionError

115. What type of error will this code produce?

print(10 + "5")
A) SyntaxError
B) NameError
C) TypeError
D) IndexError

Answer: C) TypeError

116. What happens if a variable is used before being assigned a value?

A) SyntaxError
B) TypeError
C) NameError
D) KeyError

Answer: C) NameError

117. What error occurs when you try to access an index that doesn’t exist in a list?

A) KeyError
B) ValueError
C) IndexError
D) AttributeError

Answer: C) IndexError

118. What will happen when the following code is executed?

x = int("Hello")

A) SyntaxError
B) TypeError
C) ValueError
D) KeyError

Answer: C) ValueError
119. Which of the following will cause a KeyError?

A) Accessing a dictionary key that does not exist


B) Dividing by zero
C) Using an undefined variable
D) Using a variable of the wrong type

Answer: A) Accessing a dictionary key that does not exist

120. What type of error occurs when trying to open a file that does not exist?

A) FileNotFoundError
B) ImportError
C) SyntaxError
D) KeyError

Answer: A) FileNotFoundError

121. What will happen if you try to import a module that does not exist?

A) SyntaxError
B) ModuleNotFoundError
C) TypeError
D) KeyError

Answer: B) ModuleNotFoundError

122. What happens when an infinite recursion occurs in a Python program?

A) The program runs forever


B) The program crashes with a RecursionError
C) The program automatically stops after a few iterations
D) No error occurs

Answer: B) The program crashes with a RecursionError


123. Which error is raised when trying to call a method that does not exist for an object?

A) TypeError
B) AttributeError
C) IndexError
D) ValueError

Answer: B) AttributeError

124. What will be the output of this code?

d = {"name": "Pramod"}
print(d["age"])

A) "None"
B) "0"
C) KeyError
D) IndexError

Answer: C) KeyError

125. What will happen when executing the following code?

f = open("non_existent_file.txt", "r")

A) It will create a new file


B) It will throw a FileNotFoundError
C) It will return None
D) It will print an empty string

Answer: B) It will throw a FileNotFoundError

126. What type of error occurs when an operation is performed on an unsupported data type?

A) SyntaxError
B) ValueError
C) TypeError
D) IndexError

Answer: C) TypeError
127. What happens when a function returns a value but the caller treats it as a different type?

A) ValueError
B) TypeError
C) SyntaxError
D) IndexError

Answer: B) TypeError

128. What type of error occurs when a function is called with the wrong number of arguments?

A) TypeError
B) SyntaxError
C) KeyError
D) AttributeError

Answer: A) TypeError

129. What will happen when this code is executed?

try:
x = 1 / 0
except ValueError:
print("Value error occurred")

A) "Value error occurred" will be printed


B) ZeroDivisionError will be raised
C) The program will continue without error
D) "ZeroDivisionError handled" will be printed

Answer: B) ZeroDivisionError will be raised

130. What is the best way to handle runtime errors in Python?

A) Ignoring the error


B) Using try-except blocks
C) Debugging with print statements only
D) Restarting the program manually
Answer: B) Using try-except blocks

131. Which of the following will NOT cause a runtime error?

A) print("Hello" + 5)
B) print(10 / 2)
C) int("hello")
D) open("unknown.txt", "r")

Answer: B) print(10 / 2)

MCQs on Logical Errors in Python

132. What is a logical error in Python?

A) An error that occurs due to incorrect syntax


B) An error that causes a program to crash
C) An error that allows the program to run but gives incorrect results
D) An error that occurs only at runtime

Answer: C) An error that allows the program to run but gives incorrect results

133. Which of the following best describes a logical error?

A) The program does not compile


B) The program runs but produces an incorrect output
C) The program throws an exception
D) The program crashes before execution

Answer: B) The program runs but produces an incorrect output

134. Which of the following is an example of a logical error?

A) Using = instead of == in a condition


B) Dividing by zero
C) Accessing an undefined variable
D) Incorrect indentation
Answer: A) Using = instead of == in a condition

135. What is the best way to detect logical errors in a Python program?

A) Using a debugger
B) Using try-except blocks
C) Running the program and verifying the output manually
D) Relying on Python to detect them automatically

Answer: C) Running the program and verifying the output manually

136. What will be the output of the following code?


x = 10
y = 5
if x > y:
print("x is smaller than y")

A) "x is smaller than y"


B) "x is greater than y"
C) SyntaxError
D) No output

Answer: A) "x is smaller than y" (which is incorrect due to a logical error)

137. What type of error is present in the following code?

def add(a, b):


return a - b
print(add(5, 3))

A) Syntax error
B) Logical error
C) Runtime error
D) Name error

Answer: B) Logical error (subtraction is used instead of addition)


138. How can logical errors be avoided in Python?

A) Writing clear and structured code


B) Using print statements for debugging
C) Performing proper testing
D) All of the above

Answer: D) All of the above

139. What will be the output of the following code?

for i in range(5):
print(i + 1)

A) 0 1 2 3 4
B) 1 2 3 4 5
C) 1 3 5 7 9
D) None of the above

Answer: B) 1 2 3 4 5 (If the intended output was 0 to 4, then this is a logical error)

140. Which of the following statements is true about logical errors?

A) Logical errors are easier to find than syntax errors


B) Logical errors are detected by the Python interpreter
C) Logical errors can only be detected by testing the program output
D) Logical errors prevent a program from executing

Answer: C) Logical errors can only be detected by testing the program output

141. What kind of error does the following code contain?

def is_even(num):
return num % 2 == 1

print(is_even(4))

A) Syntax error
B) Logical error
C) Runtime error
D) No error
Answer: B) Logical error (the condition should be num % 2 == 0 to check for even numbers)

Multiple Choice Questions (MCQs) on Semantic Errors

Semantic errors occur when the program runs without crashing but produces incorrect or
unintended results due to incorrect logic or meaning in the code.

142. What is a semantic error in Python?

A) An error due to incorrect syntax


B) An error that prevents the program from running
C) An error where the program runs but produces incorrect results
D) An error detected by the Python interpreter

Answer: C) An error where the program runs but produces incorrect results

143. Which of the following is an example of a semantic error?

A) Using = instead of == in a condition


B) Forgetting to close a parenthesis
C) Dividing by zero
D) Using an undefined variable

Answer: A) Using = instead of == in a condition

144. What will be the output of the following code?


def multiply(a, b):
return a + b

print(multiply(3, 4))

A) 7
B) 12
C) Error
D) None

Answer: A) 7 (Semantic error: the function should multiply, but it adds instead)
145. How can semantic errors be detected?

A) By the Python interpreter


B) By running the program and checking the output
C) By using try-except blocks
D) By syntax highlighting in an IDE

Answer: B) By running the program and checking the output

146. What kind of error is in the following code?

def area_of_rectangle(length, width):


return 2 * (length + width)

print(area_of_rectangle(5, 4))

A) Syntax error
B) Runtime error
C) Semantic error
D) No error

Answer: C) Semantic error (The formula should be length * width instead of 2 * (length +
width))

147. What will be the output of the following code?

x = 10
y = 5
if x < y:
print("x is greater than y")
else:
print("x is smaller than y")

A) "x is greater than y"


B) "x is smaller than y"
C) No output
D) Error

Answer: B) "x is smaller than y" (Semantic error: incorrect message for the condition)
148. How do semantic errors differ from syntax errors?

A) Semantic errors prevent the code from running, but syntax errors do not
B) Syntax errors cause runtime crashes, while semantic errors do not
C) Semantic errors produce incorrect results but do not stop the program from running
D) There is no difference between them

Answer: C) Semantic errors produce incorrect results but do not stop the program from running

149. Which of the following is NOT a semantic error?

A) Using the wrong formula in a calculation


B) Using an incorrect comparison operator
C) Forgetting a colon at the end of a function definition
D) Assigning an incorrect value to a variable

Answer: C) Forgetting a colon at the end of a function definition (This is a syntax error, not a
semantic error)

150. What will happen when the following code runs?


def is_odd(num):
return num % 2 == 0

print(is_odd(5))

A) True
B) False
C) Error
D) None

Answer: B) False (Semantic error: The function is named is_odd, but it checks for even
numbers)

151. What is the best way to avoid semantic errors?

A) Using try-except blocks


B) Testing the program thoroughly
C) Using syntax highlighting in an editor
D) Relying on Python to detect them automatically

Answer: B) Testing the program thoroughly


MCQs on Type Errors in Python

A TypeError in Python occurs when an operation or function is applied to an object of an


inappropriate type.

152. What is a TypeError in Python?

A) An error that occurs due to incorrect indentation


B) An error when an operation is performed on an incompatible data type
C) An error caused by a missing import statement
D) An error caused by accessing an undefined variable

Answer: B) An error when an operation is performed on an incompatible data type

153. Which of the following will raise a TypeError?

A) print(10 / 2)
B) print("10" + 5)
C) print([1, 2, 3] + [4, 5, 6])
D) print("Hello" * 3)

Answer: B) print("10" + 5) (Cannot concatenate a string with an integer)

154. What will be the output of the following code?


x = "Hello"
y = x + 5
print(y)

A) "Hello5"
B) 5Hello
C) Hello 5
D) TypeError

Answer: D) TypeError (Cannot add a string and an integer)

155. Which of the following function calls will NOT result in a TypeError?

A) int("42")
B) len(100)
C) 5 + "hello"
D) sum(["1", "2", "3"])

Answer: A) int("42") (Correctly converts a string to an integer)

156. What will happen when executing the following code?


x = [1, 2, 3]
y = x * "2"
print(y)

A) [1, 2, 3, 1, 2, 3]
B) TypeError
C) "2,2,2"
D) None

Answer: B) TypeError (Cannot multiply a list by a string)

157. What is the cause of the TypeError in the following code?


def add_numbers(a, b):
return a + b

print(add_numbers(10, "5"))

A) The function is not defined properly


B) Python does not support functions
C) String and integer cannot be added directly
D) The function is missing a return statement

Answer: C) String and integer cannot be added directly

158. Which of the following expressions will raise a TypeError?

A) print(len([1, 2, 3]))
B) print(len("Hello"))
C) print(len(42))
D) print(len({"a": 1, "b": 2}))

Answer: C) print(len(42)) (Integers do not have a length)


159. What is the output of the following code?
x = (1, 2, 3)
x[0] = 10
print(x)

A) (10, 2, 3)
B) TypeError
C) None
D) (1, 2, 3, 10)

Answer: B) TypeError (Tuples are immutable and cannot be modified)

160. Which of the following will cause a TypeError?

A) x = float("3.14")
B) y = str(10)
C) z = 10 + "20"
D) a = list((1, 2, 3))

Answer: C) z = 10 + "20" (Cannot add an integer and a string)

161. What will be the output of the following code?

print(abs("10"))

A) 10
B) -10
C) TypeError
D) None

Answer: C) TypeError (The abs() function only works on numbers, not strings)

MCQs on NameError in Python

162. What is a NameError in Python?

A) An error due to incorrect syntax


B) An error when an undefined variable or function is accessed
C) An error that occurs during type mismatches
D) An error caused by dividing by zero
Answer: B) An error when an undefined variable or function is accessed

163. Which of the following will raise a NameError?

A) print("Hello, World!")
B) x = 10; print(x)
C) print(y) (when y is not defined)
D) len([1, 2, 3])

Answer: C) print(y) (when y is not defined)

164. What will be the output of the following code?


def my_function():
print(x)

my_function()

A) None
B) NameError
C) 0
D) "x"

Answer: B) NameError (Variable x is not defined inside or outside the function)

165. How can a NameError be avoided?

A) By ensuring variables are defined before use


B) By using try-except blocks
C) By checking variable names for typos
D) All of the above

Answer: D) All of the above

166. What happens when you try to access a variable that is not defined?

A) The program prints None


B) The program runs but ignores the undefined variable
C) A NameError is raised
D) The program crashes without an error message
Answer: C) A NameError is raised

167. What will happen when executing the following code?


print(name)
name = "Pramod"

A) "Alice"
B) None
C) NameError
D) UndefinedVariableError

Answer: C) NameError (Variable name is used before assignment)

168. What will be the output of the following code?

def greet():
print(message)

message = "Hello"
greet()

A) "Hello"
B) None
C) NameError
D) SyntaxError

Answer: A) "Hello" (Since message is defined before the function is called)

169. Which of the following scenarios will NOT cause a NameError?

A) Using a variable before assigning it a value


B) Calling a function before defining it
C) Importing a module that does not exist
D) Accessing a variable inside a function when it's defined globally

Answer: D) Accessing a variable inside a function when it's defined globally

170. What will happen when executing the following code?

def my_func():
x = 5
print(x)

A) 5
B) None
C) NameError
D) SyntaxError

Answer: C) NameError (Variable x is defined inside the function and not accessible outside)

171. Which of the following will raise a NameError?

A) x = 10; print(x)
B) print(len("Hello"))
C) print(math.sqrt(25)) (without importing math)
D) list1 = [1,2,3]; print(list1[0])

Answer: C) print(math.sqrt(25)) (without importing math)

172. What will be the output of the following code?

def example():
print(value)
value = 10

example()

A) 10
B) None
C) NameError
D) UnboundLocalError

Answer: D) UnboundLocalError (Variable value is referenced before assignment inside the


function)

173. What should you do to fix a NameError?

A) Define the variable before using it


B) Check for typos in variable names
C) Import required modules before using them
D) All of the above
Answer: D) All of the above

174. What will be the output of the following code?

def display():
print(number)

number = 20
display()

A) 20
B) None
C) NameError
D) RuntimeError

Answer: A) 20 (The variable number is defined before calling the function)

175. What will be the output of the following code?

def test():
print(value)

test()
value = 15

A) 15
B) None
C) NameError
D) SyntaxError

Answer: C) NameError (Variable value is defined after the function call)

176. What happens when you try to access a global variable inside a function without
declaring it first?

A) The function can access the variable normally


B) The function creates a new local variable
C) A NameError is raised
D) The function ignores the variable

Answer: A) The function can access the variable normally (if the variable is defined before
function execution)
MCQs on IndexError in Python

177. What is an IndexError in Python?

A) An error that occurs when an operation is performed on an incompatible data type


B) An error that occurs when accessing an index that does not exist in a sequence
C) An error caused by missing parentheses in function calls
D) An error raised when dividing by zero

Answer: B) An error that occurs when accessing an index that does not exist in a sequence

178. Which of the following will raise an IndexError?

A) my_list = [1, 2, 3]; print(my_list[1])


B) my_tuple = (10, 20, 30); print(my_tuple[3])
C) my_str = "Python"; print(my_str[2])
D) my_dict = {"a": 1, "b": 2}; print(my_dict["a"])

Answer: B) my_tuple = (10, 20, 30); print(my_tuple[3]) (Index 3 is out of range for
the tuple)

179. What will be the output of the following code?


numbers = [10, 20, 30]
print(numbers[3])

A) 30
B) None
C) IndexError
D) 0

Answer: C) IndexError (Valid indices are 0, 1, 2, but 3 is out of range)

180. Which of the following will NOT raise an IndexError?

A) x = "hello"; print(x[4])
B) y = [1, 2, 3, 4]; print(y[2])
C) z = (5, 6, 7); print(z[3])
D) a = []; print(a[0])
Answer: B) y = [1, 2, 3, 4]; print(y[2]) (Index 2 is valid for this list)

181. What will be the output of the following code?


words = ["Python", "Java", "C++"]
print(words[-4])

A) "Python"
B) "C++"
C) None
D) IndexError

Answer: D) IndexError (Valid negative indices are -1, -2, -3; -4 is out of range)

182. How can you avoid an IndexError when working with lists?

A) Always use positive indices


B) Ensure the index is within the valid range before accessing it
C) Avoid using lists in Python
D) Use try-except blocks to catch the error

Answer: B) Ensure the index is within the valid range before accessing it

183. What will happen when executing the following code?


my_list = [10, 20, 30]
print(my_list[-1])

A) 10
B) 30
C) IndexError
D) None

Answer: B) 30 (Negative indexing starts from the end, so -1 refers to the last element)

184. What will be the output of the following code?


data = [5, 10, 15, 20]
index = len(data)
print(data[index])
A) 20
B) None
C) IndexError
D) 5

Answer: C) IndexError (Valid indices are 0 to len(data) - 1, but len(data) is out of range)

185. How can you safely access an element in a list without causing an IndexError?

A) Always use negative indices


B) Use the try-except block to handle IndexError
C) Avoid using lists
D) Use break statements in loops

Answer: B) Use the try-except block to handle IndexError

186. What will be the output of the following code?


items = ["apple", "banana", "cherry"]
try:
print(items[5])
except IndexError:
print("Index out of range")

A) "cherry"
B) None
C) IndexError
D) "Index out of range"

Answer: D) "Index out of range" (The IndexError is caught by the except block)

MCQs on AttributeError

187. What is an AttributeError in Python?

A) An error caused by an undefined variable


B) An error that occurs when an invalid attribute is accessed on an object
C) An error due to incorrect syntax in Python
D) An error raised when a list index is out of range

Answer: B) An error that occurs when an invalid attribute is accessed on an object


188. Which of the following will raise an AttributeError?

A) x = 10; print(x.real)
B) "hello".upper()
C) numbers = [1, 2, 3]; numbers.append(4)
D) y = 3.14; y.append(2)

Answer: D) y = 3.14; y.append(2) (float objects do not have an append() method)

189. What will be the output of the following code?


num = 42
print(num.lower())

A) "42"
B) "42".lower()
C) AttributeError
D) None

Answer: C) AttributeError (int objects do not have a lower() method)

190. Which of the following will NOT raise an AttributeError?

A) "Hello".capitalize()
B) data = [1, 2, 3]; data.sort()
C) my_tuple = (5, 10, 15); my_tuple.append(20)
D) val = 3.14; val.upper()

Answer: A) "Hello".capitalize() (Valid string method)

191. What happens when you access an attribute that does not exist for an object?

A) The program runs without errors


B) The program raises an AttributeError
C) The program prints None
D) The program automatically creates the attribute

Answer: B) The program raises an AttributeError


192. What will be the output of the following code?
class Car:
def __init__(self, brand):
self.brand = brand

c = Car("Toyota")
print(c.color)

A) "Toyota"
B) None
C) AttributeError
D) ""

Answer: C) AttributeError (color attribute is not defined in the Car class)

193. How can you avoid an AttributeError when accessing object attributes?

A) Always use integer values for attributes


B) Check if an attribute exists using hasattr(object, "attribute") before accessing it
C) Use only built-in data types
D) Convert attributes to strings before accessing them

Answer: B) Check if an attribute exists using hasattr(object, "attribute") before


accessing it

194. What will be the output of the following code?


text = "Python Programming"
print(text.append(" is fun"))

A) "Python Programming is fun"


B) None
C) AttributeError
D) "Python Programmingappend is fun"

Answer: C) AttributeError (Strings do not have an append() method)

195. What is the cause of the AttributeError in the following code?


x = None
print(x.upper())
A) NoneType object has no method upper()
B) None is a valid string
C) upper() is not a valid method in Python
D) The code will run without errors

Answer: A) NoneType object has no method upper()

196. How can you handle an AttributeError in Python?

A) By using a try-except block


B) By using a while loop
C) By converting the object into an integer
D) By using a for loop

Answer: A) By using a try-except block

MCQs on ImportError

197. What is an ImportError in Python?

A) An error that occurs when a module is not found or cannot be imported properly
B) An error due to incorrect syntax in Python
C) An error that occurs when accessing an invalid attribute of an object
D) An error caused by an infinite loop

Answer: A) An error that occurs when a module is not found or cannot be imported properly

198. Which of the following will raise an ImportError?

A) import os
B) import math
C) import non_existent_module
D) from datetime import datetime

Answer: C) import non_existent_module (This module does not exist)

199. What will be the output of the following code?


import mymodule

(Assume mymodule is not installed or not in the script's directory.)


A) None
B) ImportError
C) "Module imported successfully"
D) SyntaxError

Answer: B) ImportError (Python cannot find mymodule)

200. Which of the following is NOT a reason for an ImportError?

A) The module does not exist


B) The module name is misspelled
C) The module is not installed
D) The module contains syntax errors

Answer: D) The module contains syntax errors (This would raise a SyntaxError, not an
ImportError)

201. What is the difference between ImportError and ModuleNotFoundError?

A) ImportError occurs when a module is found but cannot be imported, while


ModuleNotFoundError occurs when a module is missing
B) They are the same error in Python
C) ModuleNotFoundError occurs only in Python 2
D) ImportError is raised only when importing built-in modules

Answer: A) ImportError occurs when a module is found but cannot be imported, while
ModuleNotFoundError occurs when a module is missing

202. What will be the output of the following code?


try:
import randommodule
except ImportError:
print("Module not found!")

A) "Module not found!"


B) ImportError
C) "randommodule imported successfully"
D) SyntaxError

Answer: A) "Module not found!" (The ImportError is caught by the except block)
203. How can you avoid an ImportError in Python?

A) Ensure the module is installed


B) Check for typos in the module name
C) Verify that the module is in the correct directory
D) All of the above

Answer: D) All of the above

204. What will be the output of the following code?


from math import square

A) No output
B) ImportError
C) ModuleNotFoundError
D) None

Answer: B) ImportError (math module exists, but square function does not exist in it)

205. Which command should you use to install a missing module and avoid ImportError?

A) install module_name
B) python install module_name
C) pip install module_name
D) import module_name

Answer: C) pip install module_name

206. What will be the output of the following code if pandas is not installed?
import pandas

A) ModuleNotFoundError
B) SyntaxError
C) None
D) IndexError

Answer: A) ModuleNotFoundError (Because pandas is not installed)


(MCQs) on "Memory Errors"

201. What is a common cause of memory leaks in Python?

a) Improper use of global variables


b) Forgetting to close files
c) Circular references in objects
d) Using the del statement

Answer: c) Circular references in objects

202. How can memory leaks be detected in a Python program?

a) Using time.sleep()
b) Using gc.collect()
c) Using a memory profiler like memory_profiler
d) Increasing system RAM

Answer: c) Using a memory profiler like memory_profiler

203. What happens when Python runs out of memory?

a) The program continues running but slows down


b) Python automatically allocates more memory
c) The program raises a MemoryError
d) The program starts using virtual memory

Answer: c) The program raises a MemoryError

204. Which Python module helps in automatic garbage collection?

a) os
b) sys
c) gc
d) re

Answer: c) gc
205. What is a circular reference in Python?

a) When a variable refers to itself


b) When two or more objects reference each other, preventing garbage collection
c) When a function calls itself recursively
d) When memory is freed before use

Answer: b) When two or more objects reference each other, preventing garbage collection

206. How can you manually trigger garbage collection in Python?

a) sys.collect()
b) gc.collect()
c) os.cleanup()
d) memory.flush()

Answer: b) gc.collect()

207. Which of the following can help reduce memory consumption in Python?

a) Using generators instead of lists


b) Using deep copies instead of shallow copies
c) Using a large number of global variables
d) Using infinite loops

Answer: a) Using generators instead of lists

208. What is a common issue when handling large data structures like lists and
dictionaries in Python?

a) Python automatically deletes them after use


b) They may consume excessive memory if not managed properly
c) They cause syntax errors
d) They prevent garbage collection

Answer: b) They may consume excessive memory if not managed properly


209. What does the del statement do in Python?

a) It permanently removes an object from memory


b) It sets an object reference to None, but may not free memory immediately
c) It forces garbage collection immediately
d) It prevents memory leaks

Answer: b) It sets an object reference to None, but may not free memory immediately

210. What is the best way to handle large files in Python without consuming too
much memory?

a) Load the entire file into a list


b) Read the file line by line using a generator (yield)
c) Convert the file into a dictionary before processing
d) Use deep copies of the file contents

Answer: b) Read the file line by line using a generator (yield)

(MCQs) on "Overflow Errors"

211. What is an OverflowError in Python?

a) When a variable is assigned an incorrect data type


b) When a calculation exceeds the maximum limit of a numeric type
c) When a function is called recursively too many times
d) When Python runs out of memory

Answer: b) When a calculation exceeds the maximum limit of a numeric type

212. In which situation is an OverflowError most likely to occur in Python?

a) When dividing by zero


b) When performing operations with extremely large floating-point numbers
c) When indexing a list beyond its range
d) When converting a string to an integer
Answer: b) When performing operations with extremely large floating-point numbers

213. How can you avoid an OverflowError in Python?

a) Use the int data type instead of float


b) Use try-except to catch and handle the error
c) Convert large numbers to strings
d) Restart the Python interpreter

Answer: b) Use try-except to catch and handle the error

214. Which Python data type is least likely to cause an OverflowError?

a) float
b) int
c) complex
d) bool

Answer: b) int (because Python integers have arbitrary precision)

215. What happens when an integer calculation exceeds the maximum value in
Python?

a) Python raises an OverflowError


b) The integer wraps around to the minimum value
c) Python automatically converts it to a long integer
d) Python allows unlimited integer size without error

Answer: d) Python allows unlimited integer size without error

216. Which Python module can help handle large numbers without overflow
issues?

a) math
b) decimal
c) os
d) sys
Answer: b) decimal

217. What will be the output of the following code?


import math
print(math.exp(1000))

a) A very large number


b) OverflowError: math range error
c) inf
d) None

Answer: b) OverflowError: math range error

218. How can you prevent an OverflowError when computing large exponents?

a) Use the decimal module


b) Use math.log instead of direct exponentiation
c) Use try-except to handle errors
d) All of the above

Answer: d) All of the above

219. What is the maximum size of an integer in Python?

a) 2³¹ - 1
b) 2⁶³ - 1
c) 10¹⁸
d) No fixed limit (limited by available memory)

Answer: d) No fixed limit (limited by available memory)

220. What happens when a floating-point operation exceeds the limit in Python?

a) It results in inf (infinity)


b) It raises an OverflowError
c) The program crashes
d) The number is converted to an integer
Answer: a) It results in inf (infinity)

221. What will be the output of the following code?


import sys
print(sys.float_info.max * 2)

a) inf
b) A very large number
c) OverflowError
d) 0

Answer: a) inf

222. Which function helps control the precision of floating-point calculations to


avoid overflow?

a) round()
b) decimal.Decimal()
c) int()
d) float()

Answer: b) decimal.Decimal()

223. What is the best way to handle an OverflowError when working with large
numbers?

a) Reduce the number of decimal places


b) Convert the numbers to integers
c) Use exception handling (try-except)
d) Store the numbers as strings

Answer: c) Use exception handling (try-except)

224. Which of the following expressions may cause an OverflowError?


a) math.factorial(1000)
b) 2 ** 1000
c) math.exp(1000)
d) 10 / 3

Answer: c) math.exp(1000)

225. What will be the output of the following code?


import math
try:
print(math.exp(2000))
except OverflowError:
print("Overflow occurred")

a) A very large number


b) Overflow occurred
c) None
d) inf

Answer: b) Overflow occurred

(MCQs) on "Key Errors"


226. What is a KeyError in Python?

a) An error that occurs when a key is missing in a dictionary


b) An error caused by an incorrect file path
c) An error that occurs when a variable is not defined
d) An error that happens when a list index is out of range

Answer: a) An error that occurs when a key is missing in a dictionary

227. How can you avoid a KeyError when accessing a dictionary?

a) Use dict.get(key) instead of dict[key]


b) Use a try-except block
c) Check if the key exists using if key in dict
d) All of the above

Answer: d) All of the above


228. What happens if you try to access a non-existent key using my_dict[key]?

a) Returns None
b) Raises a KeyError
c) Returns an empty dictionary
d) Creates a new key-value pair

Answer: b) Raises a KeyError

229. How does the get() method help in preventing KeyErrors?

a) It returns None if the key is not found instead of raising an error


b) It automatically creates the key in the dictionary
c) It raises an error when a key is not found
d) It deletes the key from the dictionary

Answer: a) It returns None if the key is not found instead of raising an error

230. What will be the output of the following code?


my_dict = {'a': 1, 'b': 2}
print(my_dict.get('c'))

a) KeyError
b) None
c) 0
d) 'c'

Answer: b) None

231. What will be the output of the following code?


my_dict = {'x': 100, 'y': 200}
print(my_dict.get('z', 'Not Found'))

a) KeyError
b) 'Not Found'
c) None
d) 0

Answer: b) 'Not Found'

232. Which method can be used to check if a key exists in a dictionary before
accessing it?

a) dict.exists(key)
b) if key in dict:
c) dict.contains(key)
d) dict.has_key(key)

Answer: b) if key in dict:

233. What is the best way to handle a KeyError in a dictionary lookup?

a) Use try-except to catch the KeyError


b) Use the get() method
c) Check key existence with in operator
d) All of the above

Answer: d) All of the above

234. What will be the output of this code?


my_dict = {'name': 'Alice', 'age': 25}
try:
print(my_dict['gender'])
except KeyError:
print("Key not found")

a) KeyError
b) 'gender'
c) 'Key not found'
d) None

Answer: c) 'Key not found'


235. How can you safely remove a key from a dictionary without causing a
KeyError?

a) Use del my_dict[key]


b) Use my_dict.pop(key, None)
c) Use my_dict.remove(key)
d) Use my_dict.clear(key)

Answer: b) Use my_dict.pop(key, None)

236. What does the setdefault() method do in dictionaries?

a) Raises a KeyError if the key is missing


b) Returns the key's value if found, otherwise sets and returns a default value
c) Deletes the key from the dictionary
d) Converts the dictionary to a set

Answer: b) Returns the key's value if found, otherwise sets and returns a default value

237. What will be the output of this code?


my_dict = {'x': 5}
print(my_dict.setdefault('y', 10))
print(my_dict)

a) KeyError
b) None
c) 10 and {'x': 5, 'y': 10}
d) 5 and {'x': 5, 'y': 10}

Answer: c) 10 and {'x': 5, 'y': 10}

238. What happens if you try to update a dictionary using update() with a key
that does not exist?

a) Raises a KeyError
b) Adds the new key-value pair to the dictionary
c) Ignores the update
d) Returns None
Answer: b) Adds the new key-value pair to the dictionary

239. How can you iterate over dictionary keys safely without causing a
KeyError?

a) Use for key in dict.keys()


b) Use try-except for missing keys
c) Use .get() instead of []
d) All of the above

Answer: d) All of the above

240. What will be the output of this code?


my_dict = {'a': 1, 'b': 2}
print(my_dict.get('c', 3))

a) KeyError
b) None
c) 3
d) 'c'

Answer: c) 3

Basic Algorithm MCQs

241. What is an algorithm?

A) A programming language
B) A step-by-step procedure to solve a problem
C) A type of computer
D) A mathematical equation

Answer: B) A step-by-step procedure to solve a problem

242. What are the key characteristics of an algorithm?

A) It must be ambiguous
B) It must have a clear stopping point
C) It should be infinitely long
D) It must be slow

Answer: B) It must have a clear stopping point

243. Which of the following is NOT a property of an algorithm?

A) Finiteness
B) Ambiguity
C) Input and Output
D) Effectiveness

Answer: B) Ambiguity

244. What is the purpose of an algorithm?

A) To increase errors in a program


B) To provide a systematic way to solve a problem
C) To make programming harder
D) To slow down execution

Answer: B) To provide a systematic way to solve a problem

245. Which of the following best describes the time complexity of an algorithm?

A) The amount of time an algorithm takes to execute


B) The number of errors in an algorithm
C) The memory required by an algorithm
D) The programming language used

Answer: A) The amount of time an algorithm takes to execute

246. What is the best case time complexity of the Linear Search algorithm?

A) O(n)
B) O(1)
C) O(n²)
D) O(log n)
Answer: B) O(1)

247. Which of the following sorting algorithms has the worst-case time complexity of O(n²)?

A) Merge Sort
B) QuickSort
C) Bubble Sort
D) Heap Sort

Answer: C) Bubble Sort

248. What is the purpose of a flowchart in algorithm design?

A) To write code
B) To create hardware
C) To visually represent the steps of an algorithm
D) To slow down execution

Answer: C) To visually represent the steps of an algorithm

249. Which data structure is used for implementing recursion in an algorithm?

A) Queue
B) Stack
C) Linked List
D) Array

Answer: B) Stack

250. What is the primary goal of analyzing an algorithm?

A) To check if the algorithm is fun


B) To determine efficiency in terms of time and space
C) To compare different programming languages
D) To count the number of lines in the code

Answer: B) To determine efficiency in terms of time and space


251. What does Big O notation represent?

A) The name of an algorithm


B) The worst-case time complexity of an algorithm
C) The best-case time complexity of an algorithm
D) The number of inputs in an algorithm

Answer: B) The worst-case time complexity of an algorithm

252. What is the first step in solving a problem using an algorithm?

A) Writing the code


B) Understanding the problem
C) Choosing a random solution
D) Ignoring the problem

Answer: B) Understanding the problem

253. Which searching algorithm works best with sorted data?

A) Linear Search
B) Binary Search
C) Bubble Sort
D) Depth-First Search

Answer: B) Binary Search

254. Which sorting algorithm follows the divide and conquer technique?

A) Bubble Sort
B) Merge Sort
C) Selection Sort
D) Insertion Sort

Answer: B) Merge Sort


255. What does "space complexity" of an algorithm refer to?

A) The time taken by an algorithm


B) The amount of memory required by an algorithm
C) The number of errors in an algorithm
D) The programming language used

Answer: B) The amount of memory required by an algorithm

256. Which of the following is a searching algorithm?

A) Bubble Sort
B) Merge Sort
C) Binary Search
D) QuickSort

Answer: C) Binary Search

257. Which algorithm is used to find the shortest path in a graph?

A) Merge Sort
B) Dijkstra’s Algorithm
C) Bubble Sort
D) QuickSort

Answer: B) Dijkstra’s Algorithm

258. Which of the following is NOT an algorithm design technique?

A) Divide and Conquer


B) Dynamic Programming
C) Greedy Approach
D) Debugging

Answer: D) Debugging
259. What is the worst-case time complexity of QuickSort?

A) O(n log n)
B) O(n²)
C) O(n)
D) O(log n)

Answer: B) O(n²)

260. Which of the following problems is solved using recursion?

A) Binary Search
B) Fibonacci Sequence
C) Tower of Hanoi
D) All of the above

Answer: D) All of the above

Basic Flowchart MCQs

261. What is a flowchart?

A) A type of programming language


B) A graphical representation of an algorithm
C) A hardware diagram
D) A type of mathematical formula

Answer: B) A graphical representation of an algorithm

262. Which symbol is used to represent the start and end of a flowchart?

A) Rectangle
B) Oval (Ellipse)
C) Diamond
D) Parallelogram

Answer: B) Oval (Ellipse)


263. What is the purpose of a flowchart?

A) To make coding more complex


B) To represent an algorithm visually
C) To replace coding
D) To confuse programmers

Answer: B) To represent an algorithm visually

264. Which flowchart symbol is used for decision-making?

A) Rectangle
B) Oval
C) Diamond
D) Parallelogram

Answer: C) Diamond

265. Which symbol is used to represent input/output in a flowchart?

A) Oval
B) Rectangle
C) Parallelogram
D) Diamond

Answer: C) Parallelogram

266. Which symbol is used to represent a process or operation in a flowchart?

A) Rectangle
B) Parallelogram
C) Oval
D) Diamond

Answer: A) Rectangle
267. What is the direction of flow in a flowchart?

A) Random
B) Left to Right or Top to Bottom
C) Right to Left only
D) Bottom to Top

Answer: B) Left to Right or Top to Bottom

268. What does an arrow represent in a flowchart?

A) A decision
B) A connector showing the flow of steps
C) An input
D) A process

Answer: B) A connector showing the flow of steps

269. Which of the following is an advantage of using a flowchart?

A) Increases complexity
B) Makes the logic of a program easy to understand
C) Eliminates the need for coding
D) Slows down execution

Answer: B) Makes the logic of a program easy to understand

270. Which symbol is used to connect different parts of a flowchart?

A) Circle
B) Rectangle
C) Diamond
D) Parallelogram

Answer: A) Circle
271. In a flowchart, what does the parallelogram symbol represent?

A) Process
B) Decision
C) Input/Output
D) Termination

Answer: C) Input/Output

272. Which of the following is NOT a standard flowchart symbol?

A) Oval
B) Rectangle
C) Star
D) Diamond

Answer: C) Star

273. Which of the following is a limitation of using flowcharts?

A) They are difficult to interpret


B) They are time-consuming to draw for complex problems
C) They cannot be used in programming
D) They have no use in problem-solving

Answer: B) They are time-consuming to draw for complex problems

274. What is the first step in creating a flowchart?

A) Writing the code


B) Understanding the problem
C) Drawing the final flowchart
D) Implementing the solution

Answer: B) Understanding the problem


275. What should be done if a flowchart becomes too complex?

A) Stop using flowcharts


B) Use sub-processes or modular flowcharts
C) Ignore the complexity
D) Remove decision-making steps

Answer: B) Use sub-processes or modular flowcharts

276. Which type of flowchart represents the entire system at a higher level?

A) Detailed flowchart
B) System flowchart
C) Program flowchart
D) Data flowchart

Answer: B) System flowchart

277. What type of flowchart is used for representing a computer program?

A) System flowchart
B) Program flowchart
C) Data flowchart
D) Hardware flowchart

Answer: B) Program flowchart

278. In a flowchart, how is a loop represented?

A) Using a decision symbol (Diamond) with arrows looping back


B) Using a rectangle only
C) Using an oval
D) Loops cannot be represented in flowcharts

Answer: A) Using a decision symbol (Diamond) with arrows looping back


279. Which of the following tools can be used to create flowcharts?

A) Microsoft Word
B) Microsoft PowerPoint
C) Online flowchart tools like Lucidchart or Draw.io
D) All of the above

Answer: D) All of the above

280. What should a well-structured flowchart avoid?

A) Clear logic
B) Proper sequence of steps
C) Too many crossing lines and confusion
D) Proper use of symbols

Answer: C) Too many crossing lines and confusion

Basic Decision Table MCQs

281. What is a decision table?

A) A type of programming language


B) A graphical representation of an algorithm
C) A table used to represent complex decision logic
D) A type of hardware component

Answer: C) A table used to represent complex decision logic

282. What are the main components of a decision table?

A) Rows and Columns


B) Conditions and Actions
C) Inputs and Outputs
D) Loops and Functions

Answer: B) Conditions and Actions


283. What is the purpose of a decision table?

A) To make programming more difficult


B) To visually represent complex decision-making logic
C) To replace flowcharts
D) To slow down execution

Answer: B) To visually represent complex decision-making logic

284. Which of the following is NOT a part of a decision table?

A) Condition Stubs
B) Action Stubs
C) Decision Tree
D) Rules

Answer: C) Decision Tree

285. What do the "Condition Stubs" in a decision table represent?

A) The possible conditions that affect a decision


B) The final result of the decision table
C) The actions to be taken
D) The number of rules in the table

Answer: A) The possible conditions that affect a decision

286. What do the "Action Stubs" in a decision table represent?

A) The possible conditions


B) The actions taken when conditions are met
C) The number of columns in the table
D) The conditions that do not change

Answer: B) The actions taken when conditions are met


287. What do the "Rules" in a decision table represent?

A) The list of programming languages


B) The conditions and corresponding actions
C) The number of columns in the table
D) The step-by-step process of an algorithm

Answer: B) The conditions and corresponding actions

288. Which of the following is an advantage of decision tables?

A) They make complex decision-making simple and clear


B) They increase coding errors
C) They are only useful for small problems
D) They slow down decision-making

Answer: A) They make complex decision-making simple and clear

289. What is the use of the "Don't Care" condition in a decision table?

A) To make the table more complex


B) To indicate that the condition does not affect the decision
C) To reduce the number of rules
D) To increase the number of conditions

Answer: B) To indicate that the condition does not affect the decision

290. How can a decision table be converted into a program?

A) By using decision rules as conditions in an if-else statement


B) By using a flowchart only
C) By writing the program without considering the table
D) A decision table cannot be converted into a program

Answer: A) By using decision rules as conditions in an if-else statement


291. What is a Limited Entry Decision Table?

A) A table that allows only a limited number of rules


B) A table where each condition has only two possible values (Yes/No or True/False)
C) A table with unlimited conditions
D) A table used only for mathematical calculations

Answer: B) A table where each condition has only two possible values (Yes/No or True/False)

292. How many parts does a decision table typically have?

A) 2
B) 3
C) 4
D) 5

Answer: C) 4 (Condition Stubs, Condition Entries, Action Stubs, Action Entries)

293. What is an Extended Entry Decision Table?

A) A decision table with multiple condition values instead of just Yes/No


B) A table with a limited number of conditions
C) A table used only for small problems
D) A table with only one condition

Answer: A) A decision table with multiple condition values instead of just Yes/No

294. Which of the following is NOT an advantage of using a decision table?

A) Helps in identifying missing cases


B) Simplifies complex decision logic
C) Requires less memory than flowcharts
D) Can be automated for business rules

Answer: C) Requires less memory than flowcharts


295. Which software development phase commonly uses decision tables?

A) Coding
B) Testing
C) Requirement Analysis
D) Debugging

Answer: C) Requirement Analysis

296. What is the main difference between a Decision Table and a Decision Tree?

A) A Decision Table is graphical, while a Decision Tree is tabular


B) A Decision Table is tabular, while a Decision Tree is graphical
C) Both are the same
D) Decision Trees do not involve conditions

Answer: B) A Decision Table is tabular, while a Decision Tree is graphical

297. Which of the following statements is true about decision tables?

A) Decision tables help in identifying missing test cases


B) Decision tables cannot be used in real-life scenarios
C) Decision tables are only useful for small programs
D) Decision tables are never used in business applications

Answer: A) Decision tables help in identifying missing test cases

298. When should you use a decision table?

A) When conditions and outcomes are simple


B) When there are multiple conditions leading to different actions
C) When no decisions need to be made
D) When programming without logic

Answer: B) When there are multiple conditions leading to different actions


299. What is an Action Entry in a decision table?

A) A description of possible actions


B) The execution result of an algorithm
C) The entry that lists all conditions
D) The part of the table that determines the number of rules

Answer: A) A description of possible actions

300. Which field commonly uses decision tables?

A) Agriculture
B) Business Rules and Software Testing
C) Cooking
D) Music Production

Answer: B) Business Rules and Software Testing

MCQs on Structured Programming Concepts

301. What is structured programming?

A) A method of writing programs using only loops


B) A programming paradigm that emphasizes clear, readable, and organized code
C) A way to write machine code directly
D) A type of hardware programming

Answer: B) A programming paradigm that emphasizes clear, readable, and organized code

302. Which of the following is NOT a characteristic of structured programming?

A) Use of functions and procedures


B) Breaking a program into modules
C) Extensive use of GOTO statements
D) Use of loops and conditionals

Answer: C) Extensive use of GOTO statements


303. Which of the following control structures are fundamental in structured programming?

A) Sequence, Selection, Iteration


B) Input, Output, Storage
C) Compilation, Execution, Debugging
D) Arrays, Functions, Pointers

Answer: A) Sequence, Selection, Iteration

304. What does the "Sequence" control structure in structured programming refer to?

A) Executing instructions in a specific order


B) Making decisions using IF statements
C) Repeating a block of code multiple times
D) Skipping parts of a program

Answer: A) Executing instructions in a specific order

305. Which of the following is an example of the "Selection" control structure?

A) for loop
B) while loop
C) if-else statement
D) switch statement

Answer: C) if-else statement

306. Which control structure is used to repeat a block of code multiple times?

A) Sequence
B) Iteration
C) Selection
D) Compilation

Answer: B) Iteration
307. Which of the following loops is NOT available in structured programming?

A) for loop
B) while loop
C) do-while loop
D) GOTO loop

Answer: D) GOTO loop

308. What is the main advantage of structured programming?

A) Programs are easier to understand and modify


B) Programs run faster than unstructured programs
C) It eliminates the need for debugging
D) It does not require functions or procedures

Answer: A) Programs are easier to understand and modify

309. Which programming language is most closely associated with structured programming?

A) Assembly Language
B) C
C) HTML
D) Machine Language

Answer: B) C

310. What is modular programming in structured programming?

A) Writing a program as one single function


B) Breaking a program into small independent functions or modules
C) Using only loops to control program execution
D) Avoiding all types of conditional statements

Answer: B) Breaking a program into small independent functions or modules


311. Which of the following statements about structured programming is true?

A) It allows the use of the GOTO statement extensively


B) It is difficult to debug structured programs
C) It improves readability and maintainability
D) It cannot be used for large programs

Answer: C) It improves readability and maintainability

312. Which of the following is NOT a structured programming language?

A) Pascal
B) C
C) Python
D) Assembly

Answer: D) Assembly

313. What is the main problem with using the GOTO statement in a program?

A) It makes the program faster


B) It makes the program difficult to understand and maintain
C) It improves program readability
D) It increases memory usage

Answer: B) It makes the program difficult to understand and maintain

314. Which programming construct allows code execution based on a condition?

A) Sequence
B) Selection
C) Iteration
D) Compilation

Answer: B) Selection
315. What is the purpose of the "break" statement in structured programming?

A) To stop the execution of a loop or switch statement


B) To define a function
C) To jump to another part of the program
D) To create a new variable

Answer: A) To stop the execution of a loop or switch statement

316. In structured programming, what is the role of a function?

A) To store data permanently


B) To allow reusability and modularization of code
C) To replace loops
D) To make a program execute faster

Answer: B) To allow reusability and modularization of code

317. What is recursion in structured programming?

A) A loop that runs indefinitely


B) A function that calls itself
C) A way to define global variables
D) A method to stop program execution

Answer: B) A function that calls itself

318. Which of the following is NOT a benefit of structured programming?

A) Code is easier to understand


B) Code is more reusable
C) Code runs faster than machine language
D) Code is easier to debug and modify

Answer: C) Code runs faster than machine language


319. What is the purpose of the "continue" statement in structured programming?

A) To terminate the program


B) To exit the loop immediately
C) To skip the current iteration of a loop and continue with the next iteration
D) To move execution to a different function

Answer: C) To skip the current iteration of a loop and continue with the next iteration

320. Which principle of structured programming helps in reducing code duplication?

A) Using GOTO statements


B) Writing long, continuous blocks of code
C) Using functions and modular programming
D) Avoiding loops and conditional statements

Answer: C) Using functions and modular programming

MCQs on Top-down and Bottom-up Programming

321. What is a programming methodology?

A) A set of rules for writing machine code


B) A structured approach to software development
C) A method used only in AI programming
D) A way to design hardware

Answer: B) A structured approach to software development

322. What is the main principle of the top-down approach?

A) Breaking a complex problem into smaller subproblems


B) Combining small modules into a larger system
C) Writing code without any design phase
D) Using only object-oriented programming

Answer: A) Breaking a complex problem into smaller subproblems


323. What is the first step in the top-down approach?

A) Identifying the smallest functions


B) Designing the overall system before coding
C) Writing all functions first
D) Implementing detailed algorithms before structure

Answer: B) Designing the overall system before coding

324. Which of the following is a key characteristic of the bottom-up approach?

A) Starting with the high-level design and breaking it into submodules


B) Combining small, well-defined modules to form a complete system
C) Writing code without defining a structure
D) Using only procedural programming

Answer: B) Combining small, well-defined modules to form a complete system

325. In the top-down approach, how are problems typically solved?

A) By starting with the simplest components and integrating them


B) By focusing on coding first and designing later
C) By breaking down the main problem into subproblems and solving them step by step
D) By writing the entire program as a single function

Answer: C) By breaking down the main problem into subproblems and solving them step by
step

326. What is the main focus of the bottom-up approach?

A) Understanding the entire system first


B) Developing and testing small, reusable components before integrating them
C) Avoiding modularization
D) Writing the entire program in a single flow

Answer: B) Developing and testing small, reusable components before integrating them
327. Which of the following is an advantage of the top-down approach?

A) It requires minimal initial planning


B) It helps in better understanding of system architecture
C) It starts with coding and testing simultaneously
D) It focuses only on low-level details

Answer: B) It helps in better understanding of system architecture

328. Which programming paradigm is most closely related to the bottom-up approach?

A) Structured programming
B) Object-oriented programming
C) Functional programming
D) Assembly programming

Answer: B) Object-oriented programming

329. Which methodology is generally used in procedural programming languages like C?

A) Bottom-up approach
B) Top-down approach
C) Neural network approach
D) Data-driven approach

Answer: B) Top-down approach

330. In a bottom-up approach, how is the system built?

A) By defining high-level modules first


B) By writing functions first and integrating them later
C) By avoiding modularization and coding everything together
D) By skipping testing and debugging

Answer: B) By writing functions first and integrating them later


331. Which of the following is an advantage of the bottom-up approach?

A) It provides better system-level understanding from the beginning


B) It encourages reusability of components
C) It focuses only on the user interface
D) It requires no initial planning

Answer: B) It encourages reusability of components

332. Which of the following is a disadvantage of the top-down approach?

A) It makes debugging easier


B) It requires a clear understanding of the overall system from the start
C) It starts with small components
D) It encourages object-oriented design

Answer: B) It requires a clear understanding of the overall system from the start

333. Which of the following best describes the relationship between top-down and bottom-up
approaches?

A) They are completely independent and unrelated


B) They are opposing methodologies but can be used together in software development
C) Only the top-down approach is effective
D) The bottom-up approach is only used in assembly language

Answer: B) They are opposing methodologies but can be used together in software development

334. What is a key benefit of using the top-down approach in large projects?

A) It allows teams to focus on smaller, manageable parts before implementation


B) It eliminates the need for documentation
C) It avoids planning and allows developers to code immediately
D) It is only useful for small-scale projects

Answer: A) It allows teams to focus on smaller, manageable parts before implementation


335. What is the main drawback of the bottom-up approach?

A) It does not allow reusability


B) It does not provide a clear high-level view of the system in the beginning
C) It cannot be used in object-oriented programming
D) It requires the use of GOTO statements

Answer: B) It does not provide a clear high-level view of the system in the beginning

336. In which approach do developers first build and test low-level modules before combining
them into higher-level structures?

A) Top-down
B) Bottom-up
C) Waterfall
D) Agile

Answer: B) Bottom-up

337. Which of the following best represents the top-down approach in problem-solving?

A) Designing the entire architecture first and then implementing details


B) Writing random pieces of code and integrating them later
C) Avoiding modular design
D) Only focusing on small functions without considering the entire system

Answer: A) Designing the entire architecture first and then implementing details

338. Which software development model is more aligned with the top-down approach?

A) Agile Model
B) Waterfall Model
C) Spiral Model
D) Prototyping Model

Answer: B) Waterfall Model


339. How does the bottom-up approach improve code reuse?

A) By forcing developers to rewrite every function from scratch


B) By designing small modules that can be reused in different parts of the system
C) By avoiding modularity and making all code dependent on a single function
D) By focusing only on hardware implementation

Answer: B) By designing small modules that can be reused in different parts of the system

340. Which of the following is a real-world example of a bottom-up approach?

A) Designing a car by first sketching the entire structure and then creating the parts
B) Building a house by constructing each room separately and then assembling them
C) Writing a book by first drafting the entire story and then refining the details
D) Developing an application by designing the user interface first

Answer: B) Building a house by constructing each room separately and then assembling them

You might also like