WorksheetsIntroduction to Programming and Algorithms
Total questions: 112
Worksheet time: 56mins
Which statement best defines a program in computing?
A list of tasks executed by humans
A sequence of instructions for a computer
A random set of code snippets and files
A visual diagram describing data flows
In the input–processing–output model, which part corresponds to computation on received data?
Input stage performing data entry
Processing stage transforming inputs
Output stage formatting results
Storage stage archiving records
Consider the Python snippet: a = 5; b = 10; sum = a + b; print("The sum is:", sum). What will be displayed?
The sum is: a + b
The sum is: 15
The sum is: 5
The sum is: 10
Which description most accurately defines an algorithm?
A step-by-step finite process
An infinite sequence of trial steps
A casual guideline without rules
A diagram illustrating hardware
Which characteristic ensures an algorithm does not run forever?
Finiteness guaranteeing termination
Effectiveness using basic operations
Definiteness with unambiguous steps
Generality allowing many problems
Which statement reflects definiteness in a good algorithm?
Steps are unambiguous and precise
Steps require advanced hardware
Steps are optional and flexible
Steps vary by user intuition
Given an array A = [7, 3, 9] and x = 3, what index will linear search return? Assume zero-based indexing.
Return -1 because 3 is absent
Return 0 after first comparison
Return 1 when match is found
Return 2 after checking all
During linear search, what should be returned if the end of the array is reached without finding x?
Return the array length
Return the last index checked
Return -1 indicating not found
Return None to halt program
Which statement best defines a data structure in programming?
A tool for compiling Python programs
A protocol for network data transfer
A way of organizing data in memory
A method to format code comments neatly
Which list contains only linear data structures?
Dictionary, Set, Hash Table
Tree, Graph, Heap, Trie
Matrix, Tensor, Vector Space
Array, Linked List, Stack, Queue
Which category describes data arranged hierarchically with parent-child relationships?
Non-linear structures arranged hierarchically
Hash-based structures using key-value
Relational tables with SQL joins
Linear structures arranged sequentially
In Python, which data structure is the closest example of hash-based storage?
Tuple storing immutable sequences
List storing elements by index
Dictionary storing key–value pairs
Array storing contiguous integers
You need fast lookups of student details by roll number. Which structure fits best?
Dictionary mapping roll to details
Queue of incoming students
Array with sequential roll numbers
Linked list of student nodes
Which scenario most benefits from non-linear data structures like graphs?
Processing ordered tasks in a queue
Storing contiguous sensor readings
Maintaining a fixed-size circular buffer
Modeling social network connections
A dataset grows from thousands to millions of entries. What property ensures the system remains responsive?
Portability across operating systems
Scalability handling large datasets
Interactivity of the user interface
Redundancy of backup copies
For searching a value, which option correctly compares time complexities?
Unsorted linear search O(n), binary search O(log n)
Unsorted linear search O(log n), binary search O(n)
Binary search and hash lookup are both O(n)
Both unsorted and binary search are O(1)
Which statement best describes dynamic typing in Python?
Type inferred from function
Type decided at runtime
Type chosen by the interpreter once
Type fixed by variable name
Type decided at compile time
Given x = 10, which data type does x have?
str
complex
int
bool
float
Which collection is unordered in Python?
list
range
tuple
string
set
Select the correct example of a tuple literal.
{"a": 1}
{1, 2, 3}
(10)
(10, 20)
[1, 2, 3]
What do control flow statements primarily determine in a program?
Memory allocation strategy
Order in which code executes
Names of variables used
Data types of expressions
Compilation optimization level
In Python’s normal execution without control flow, code runs in which manner?
Randomly by interpreter choice
Bottom to top in files
Line by line, top to bottom
Function by function only
Statement groups by modules
Which statement executes a block only when a condition is True?
elif
for
while
if
else
Given x = -3, which output matches the code: if x > 0: print("Positive number")
No output produced
True printed
Negative number
Positive number
Error at runtime
Which option lists only numeric data types in Python?
float, str, complex
complex, tuple, int
int, bool, float
int, float, complex
int, list, float
Choose the correct literal for a dictionary with keys name and age.
{"John": "name", 25: "age"}
{"name": "John", "age": 25}
["name", "John", 25]
("name", "John", 25)
{"name", "John", "age", 25}
Which statement best explains the role of boolean expressions in conditionals?
They create new variables
They store text values
They define numeric ranges
They evaluate to True or False
They sort collections automatically
You need a collection with unique items and no order. Which type fits best?
set for uniqueness only
dict for key-value pairs
tuple for immutability
list for flexible order
string for sequence text
Which statement best describes a Python for loop?
Runs until memory is exhausted automatically
Evaluates a condition and returns True or False
Iterates over each element in a sequence
Executes code once without repetition
What does range(5) produce when used in a for loop like for i in range(5): print(i)?
Numbers 0 through 4 inclusive
Even numbers 0 to 8 inclusive
A single integer equal to 5
Numbers 1 through 5 inclusive
Which Python construct repeats a block while a condition remains True?
match statement in Python 3.10
def function with parameters
while loop with Boolean condition
for loop over a dictionary
Choose the correct output of the code: s = 'abc'; for ch in s: print(ch)
a then b then c on new lines
a b c on one line
abc on one line
Nothing because strings are not iterable
In a while loop, where should the update to the loop variable typically occur?
Only in the loop condition itself
Outside the loop before entering
Inside the loop body after condition check
Nowhere; Python updates it automatically
Identify the bug causing an infinite loop: i = 0; while i < 3: print(i)
The condition uses less-than incorrectly
Missing increment of i in the loop
print cannot be used in while loops
range should be used instead of while
Which statement correctly iterates over a list nums = [2,4,6]?
for n in nums: print(n)
for i in range(nums): print(i)
for index in 0..len(nums): print(index)
while nums: print(nums[0])
Select the best reason to use a for loop over a while loop.
When the iteration count is unknown
When preventing syntax errors in code
When iterating directly over a sequence
When needing complex conditional logic
What is the final value printed by for i in range(5): print(i)?
4
0
5
None
Which condition correctly stops a while loop that accumulates until total >= 100?
while total == 100:
while total < 100:
while total >= 100:
while total > 100:
Given nums = [1,3,5,7], what does the loop do? sum = 0; for x in nums: sum += x; print(sum)
Prints 4 because list length
Prints 16 after summing all values
Prints 7 because last element only
Raises TypeError for addition
Which statement best avoids off-by-one errors when iterating indices of a list L?
for i in range(1, len(L))
for i in range(0, len(L)+1)
for i in range(0, len(L))
for i in range(1, len(L)+1)
Which Python jump statement exits a loop immediately when triggered?
pass
stop
continue
break
In a for loop, what does continue do when a condition is met?
Repeats same iteration
Jumps two iterations
Skips current iteration
Ends the loop now
Which statement is used as a placeholder that does nothing when executed?
pass
idle
noop
halt
Consider: for i in range(10): if i == 5: break; print(i). What is the last value printed?
5
4
6
9
Given: for i in range(5): if i == 2: continue; print(i). Which single value is omitted from output?
4
1
0
2
Which best describes the loop else clause in Python?
Runs only when break occurs
Runs after normal completion
Runs when loop starts
Runs before each iteration
When does the else block on a loop NOT execute?
When the loop body is empty
When continue is used
When range is zero
When break exits the loop
Choose the correct effect of pass inside a loop body.
Restarts loop from top
Does nothing and continues
Skips printing output
Terminates loop early
You need to ignore a specific value while scanning a list but keep looping. Which statement is appropriate?
break
stop
return
continue
A while loop decrements count by 1 until count > 0. What ensures termination?
A pass statement
The else clause always
A break in the header
The decreasing state
Which output matches: for i in range(5): if i == 2: continue; print(i)
0 2 3 4
0 1 3 4
1 2 3 4 5
0 1 2 3 4
Plan a robust search loop that stops when a target is found and reports if not found. Which construct pairing is most suitable?
continue with pass
return with continue
break with loop else
pass with loop else
Which statement best defines a function in Python?
A block of reusable code for a task
A single variable storing program state
A loop construct for repeated steps
A comment explaining program logic
Which example best matches the function analogy of a coffee machine?
Input, processing, and output flow
Class inheritance and polymorphism
Thread scheduling and synchronization
File I/O buffering and caching
Which advantage of functions directly relates to writing code once and using it many times?
Abstraction of hardware calls
Code reusability across modules
Readability of variable names
Modularity of data types
Which advantage primarily makes code easier to understand for humans?
Abstraction using APIs
Modularity via packages
Maintainability with logs
Readability through structure
Which advantage helps break a program into small, logical parts?
Maintainability tools
Abstraction of logic
Modularity with functions
Reusability of blocks
Which advantage means you don’t need to know internal logic, only how to call it?
Abstraction of implementation
Reusability via libraries
Readability through comments
Maintainability with testing
Which built-in behavior does the pass statement represent in Python loops?
An immediate loop termination
A placeholder that does nothing
A pause until user input
A counter increment operation
In a for loop with an else clause, when does the else block execute?
Never in Python’s for loops
Always after each iteration
Only when loop encounters continue
Only if loop finishes without break
Given the code: for i in range(3): print(i) else: print("Loop completed"), what is the final output line?
Loop completed after 0,1,2
Break encountered at i==2
Pass prevents final message
Continue skips printing 2
Which benefit of functions most directly supports easier debugging and updates?
Modularity in design
Reusability of code
Abstraction of details
Maintainability over time
Choose the best reason to wrap repeated logic inside a function.
Reuse, readability, and maintainability
Faster CPU clock speed
Automatic memory garbage collection
Lower network latency
You’re designing a program with repeated data-cleaning steps. Which approach aligns with modularity and reusability?
Define a clean() function and call it
Copy-paste the cleaning code blocks
Write cleaning inside a while loop
Store steps in global variables
Which keyword starts the definition of a user-defined function in Python?
def keyword begins a function
func keyword declares functions
lambda keyword defines functions
return keyword starts functions
What is the primary purpose of a docstring inside a Python function?
Describe the function behavior
Import external libraries
Execute the function logic
Store temporary variables
Given def greet(name): return f"Hello, {name}!", what does print(greet("Alice")) output?
Hello, Alice!
Alice says hello
Hi there, Alice
Hello, {name}!
Which statement best describes a lambda function in Python?
Anonymous function defined with lambda
Module-level function imported from math
Class method requiring self parameter
Named function created using def
What is a common use case for lambda functions?
Short, throwaway operations
Persistent configuration files
Long, stateful procedures
Complex class hierarchies
Consider square = lambda x: x*x. What is print(square(5))?
25
10
125
5
Which built-in function returns the number of items in a list?
range() counts items
len() counts items
sum() counts items
type() counts items
For nums = [1, 2, 3, 4], what does sum(nums) return?
4 total value
9 total value
10 total value
6 total value
Which line correctly places an optional docstring in a function?
// Explains the function
# Explains the function
'''Executed by Python'''
"""Explains the function"""
Which statement about recursion is accurate?
Function must avoid any parameters
Function loops without any calls
Function always uses global variables
Function calls itself with base case
In a recursive factorial function, what is the typical base case for n?
n equals 0 or 1
n equals any prime
n equals 2 only
n equals negative one
Which code snippet best exemplifies defining and returning a value from a user-defined function?
def add(): print(a+b) only
lambda add: a+b then return
class add(): return method
def add(a,b): return a+b
Which statement best describes positional arguments in a Python function call?
Their order determines parameter mapping
They require keyword syntax in calls
Their names determine parameter mapping
They must have default values defined
Given def add(a, b): return a + b, what does print(add(10, 5)) output?
an error due to types
a tuple (10, 5)
'15' as string literal
15 as integer value
Which function call correctly uses keyword arguments for greet(name, msg)?
greet(name="Alice", msg="Hello")
greet("Hello", "Alice")
greet(msg name="Alice")
greet(msg: "Hello", name: "Alice")
In def greet(name, msg="Hello"): print(f"{msg}, {name}"), what is printed by greet("Bob")?
Hello, Bob
Good Morning, Bob
Bob, Hello
None is printed
Which choice correctly explains *args in a function definition?
Collects extra positional arguments
Creates local-only variables
Collects extra keyword arguments
Defines default parameter values
Which choice correctly explains **kwargs in a function definition?
Collects extra keyword arguments
Collects extra positional arguments
Specifies return type annotation
Forces positional-only parameters
Which statement about local scope is accurate in Python functions?
Variables defined inside a function are local
Local variables persist after function returns
Local variables are accessible from other modules
Local scope equals global module namespace
Which keyword allows a function to modify a module-level variable?
return
nonlocal
global
yield
Which keyword lets an inner function rebind a variable from an enclosing function scope?
nonlocal
global
extern
static
What does a Python return statement do inside a function?
Pauses execution like yield
Declares a global constant
Prints a value to the console
Sends a value back to the caller
Which is valid when a function needs to return multiple values to callers?
Mutate caller variables implicitly
Return a tuple of values
Use multiple return keywords
Return values via print calls
In the recursive factorial example, which condition prevents infinite recursion?
Base case if n == 0
Using keyword arguments
Returning multiple values
Defining default parameters
Which statement best describes Object-Oriented Programming in Python?
Uses objects only for storing global variables
Organizes code around objects and their interactions
Focuses only on functions and linear logic flow
Runs faster than procedural programming by default
In OOP, what are attributes of an object?
Steps of a procedural algorithm
Data describing the object's state
Reusable blocks of executable behavior
External libraries imported into classes
Which term refers to behaviors an object can perform?
Procedures of the object
Attributes of the object
Methods of the object
Modules of the object
Python supports which programming paradigms?
Event-driven paradigm only
Procedural and object-oriented paradigms
Functional and declarative paradigms
Only object-oriented paradigm
Which option correctly pairs car properties with OOP concepts?
Start(), stop() are attributes; color is a method
Brand, color, speed are attributes; start() is a method
Speed is a method; accelerate() is an attribute
Brand is a method; accelerate() is an attribute
Which is a primary advantage of OOP for large Python projects?
Improves modularity through class-based design
Eliminates the need for testing entirely
Replaces functions with global variables
Guarantees faster runtime in all cases
What does reusability mean in the context of OOP?
Objects run without any dependencies
Global variables persist between modules
Classes and methods can be used across programs
Each function must be written only once
Which statement best contrasts OOP with procedural programming?
OOP uses inheritance; procedural uses recursion
OOP organizes around objects; procedural organizes around functions
OOP forbids functions; procedural forbids objects
OOP is only for GUIs; procedural is only for scripts
Which benefit of OOP most directly supports long-term code changes?
Higher network throughput
Built-in database persistence
Maintainability through clear structure
Automatic parallel execution
A student designs a Car class with speed and color, and methods start() and stop(). What principle is being applied?
Encapsulation of data and behavior
Recursion within procedural code
Compilation into machine language
Global state management
Which example best illustrates abstraction in OOP?
Using print statements to debug low-level details
Writing a long procedural script without functions
Storing all settings in global variables for easy access
Providing a start() method without exposing engine complexity
You are refactoring a large project into classes. Which outcome aligns with OOP advantages?
All code converts to functional style
Global variables automatically disappear
Execution time always decreases significantly
Modules become easier to test and reuse
In Python OOP, what best describes a class?
Module that contains global code
Template defining object structure
Runtime copy of an instance
Function for initializing attributes
What is an object in Python OOP?
Global variable shared by all
Special method like __init__
Blueprint for many instances
Instance created from a class
Which statement about the __init__ method is correct?
Automatically runs when an object is created
Defines class variables only by default
Manually called after object creation
Returns the newly constructed class
Given class Car with def __init__(self, brand, model): self.brand=brand; self.model=model. What does print(c1.brand) output for c1=Car("Tesla","Model X")?
brand
Model X
Car
Tesla
Which benefit of OOP refers to dividing code into smaller parts like classes?
Abstraction
Modularity
Maintainability
Scalability
Which OOP benefit best matches "easier to debug and update"?
Scalability
Abstraction
Reusability
Maintainability
In class Student with __init__(self,name,roll): self.name=name; self.roll=roll, what is s.name for s=Student("Alice",101)?
Student
name
101
Alice
What distinguishes instance variables from class variables?
Class variables exist only in __init__
Instance variables belong to objects
Class variables stored per object instance
Instance variables shared across all objects
Which term refers to hiding implementation details in OOP?
Abstraction
Modularity
Reusability
Scalability
If c2=Car("BMW","i8"), what does print(c2.model) display?
Car
model
BMW
i8
Which option best explains reusability in OOP?
Classes and objects used across programs
Constructors eliminate duplicated functions
Objects created only once per runtime
Methods copy code between modules
Which OOP advantage makes the approach suitable for large projects?
Scalability
Reusability
Modularity
Abstraction
