Mettl Coding Fundamentals and Logic 4 — Questions and Answers
Question 1: What is the output of the following code? for i in range(1, 6): if i % 2 == 0: print(i, end=' ')
- 1 3 5
- 2 4 (Correct answer)
- 1 2 3 4 5
- 2 4 6
Correct answer: 2 4
The loop runs i=1 to 5; only even values (2 and 4) satisfy i%2==0.
Question 2: A variable declared inside a function in most programming languages has _____ scope.
- Global
- Local (Correct answer)
- Static
- Dynamic
Correct answer: Local
Variables declared inside a function have local scope and are not accessible outside it.
Question 3: Which of the following is an example of a runtime error?
- Missing semicolon
- Division by zero (Correct answer)
- Undeclared variable
- Type mismatch at compile time
Correct answer: Division by zero
Division by zero is detected only at runtime when the denominator is evaluated as zero.
Question 4: What does the following loop print? i = 1 while i < 32: i *= 2 print(i)
- 16
- 32 (Correct answer)
- 64
- 31
Correct answer: 32
i doubles: 1→2→4→8→16→32; the loop exits when i=32, which is then printed.
Question 5: Which principle states that a class should have only one reason to change?
- Open/Closed Principle
- Single Responsibility Principle (Correct answer)
- Liskov Substitution Principle
- Interface Segregation Principle
Correct answer: Single Responsibility Principle
The Single Responsibility Principle (SRP) states each class should have exactly one responsibility.
Question 6: What is the output of: print(bool(0), bool(''), bool([1]))?
- True True True
- False False True (Correct answer)
- False True False
- True False False
Correct answer: False False True
0 and '' are falsy, while a non-empty list [1] is truthy in Python.
Question 7: In Big-O notation, which function grows the slowest as n increases?
- O(n)
- O(n log n)
- O(log n) (Correct answer)
- O(√n)
Correct answer: O(log n)
O(log n) grows slower than O(√n), O(n), and O(n log n) for large n.
What is the output of the following code?
for i in range(1, 6):
if i % 2 == 0:
print(i, end=' ')