Unit 2: Conditional and Iterative Statements - Subjective Questions
INT108 — Python Programming • Practice Questions with Detailed Answers
20 questions
Define the modulus operator in Python. Explain its behavior with suitable examples and mention two practical applications.
The modulus operator % returns the remainder obtained when one number is divided by another.
If is divided by , then:
where is the quotient and is the remainder. In Python, a % b produces .
Examples:
17 % 5evaluates to2.20 % 4evaluates to0.7 % 10evaluates to7.
Applications:
- Checking even or odd numbers: A number
nis even whenn % 2 == 0. - Testing divisibility:
n % d == 0means thatnis divisible byd. - Cyclic operations: The expression
(index + 1) % sizecan wrap an index back to zero.
Explain how random numbers are generated in Python using the random module. Distinguish between random(), randint(), and randrange().
Python provides the random module for generating pseudo-random values. It is imported using import random.
random.random()returns a floating-point value in the interval .random.randint(a, b)returns an integer in the inclusive interval .random.randrange(start, stop, step)selects a value from the same sequence represented byrange(start, stop, step). Thestopvalue is excluded.
Examples:
import random
x = random.random() # 0.0 <= x < 1.0
y = random.randint(1, 6) # 1 through 6
z = random.randrange(2, 11, 2) # 2, 4, 6, 8, or 10These functions are commonly used in games, simulations, testing, sampling, and randomized algorithms.
What is a Boolean expression? Describe comparison operators and explain how Python evaluates truth values.
A Boolean expression is an expression whose result is either True or False.
Python comparison operators include:
==: equal to!=: not equal to<: less than>: greater than<=: less than or equal to>=: greater than or equal to
Examples:
8 > 3evaluates toTrue.5 == 7evaluates toFalse.10 != 4evaluates toTrue.
Python also interprets values in Boolean contexts. Values such as 0, 0.0, None, and empty strings or collections are considered falsy. Most other values are truthy.
Boolean expressions control the execution of conditional statements and loops.
Explain the logical operators and, or, and not with truth tables and suitable Python examples.
Logical operators combine or reverse Boolean expressions.
and operator: It is True only when both operands are true.
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
or operator: It is True when at least one operand is true.
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
not operator: It reverses a truth value: not True is False, and not False is True.
age = 20
has_id = True
can_enter = age >= 18 and has_id
is_special_case = age < 12 or age >= 60
invalid = not has_idPython uses short-circuit evaluation: and stops when it finds a falsy operand, while or stops when it finds a truthy operand.
Describe the syntax and working of if, if-else, and if-elif-else statements in Python.
Conditional statements select code according to Boolean conditions.
Simple if: The block executes only when the condition is true.
if temperature > 30:
print('Hot day')if-else: Exactly one of two blocks executes.
if number % 2 == 0:
print('Even')
else:
print('Odd')if-elif-else: Conditions are checked from top to bottom. The first true branch executes, and the remaining branches are skipped.
if score >= 90:
grade = 'A'
elif score >= 75:
grade = 'B'
elif score >= 50:
grade = 'C'
else:
grade = 'F'A colon is required after each condition, and indentation defines each controlled block.
Compare nested conditional statements with an if-elif-else ladder. Illustrate both forms with examples.
An if-elif-else ladder chooses one branch from several alternatives at the same logical level. A nested conditional places one conditional inside another and is useful when a second decision depends on the result of the first.
Ladder example:
if marks >= 80:
result = 'Distinction'
elif marks >= 50:
result = 'Pass'
else:
result = 'Fail'Nested example:
if marks >= 50:
if marks >= 80:
result = 'Pass with distinction'
else:
result = 'Pass'
else:
result = 'Fail'Comparison:
- A ladder is usually clearer for mutually exclusive alternatives.
- Nesting expresses dependent or hierarchical decisions.
- Excessive nesting reduces readability and may often be simplified using logical operators or early returns.
- Indentation is essential because it identifies which branch contains the inner condition.
Write and explain a Python program that determines whether a given year is a leap year using conditional and logical operators.
A year is a leap year when it is divisible by , or when it is divisible by but not by .
The Boolean condition is:
year = int(input('Enter a year: '))
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print('Leap year')
else:
print('Not a leap year')Explanation:
- Years divisible by
400, such as2000, are leap years. - Years divisible by
100but not400, such as1900, are not leap years. - Other years divisible by
4, such as2024, are leap years. - Parentheses make the intended grouping of logical expressions explicit.
Define a while statement. Explain initialization, condition testing, updating, and termination with an example.
A while statement repeatedly executes a block as long as its condition remains true. It is appropriate when the number of iterations is not known in advance.
A counter-controlled while loop usually contains:
- Initialization: Set the initial loop-control value.
- Condition: Decide whether another iteration should run.
- Update: Change the loop-control value.
- Termination: Stop when the condition becomes false.
count = 1
while count <= 5:
print(count)
count += 1Here, count = 1 initializes the counter, count <= 5 is tested before every iteration, and count += 1 updates it. The loop terminates when count becomes 6.
If the update is omitted, the condition may remain true forever, producing an infinite loop.
Describe sentinel-controlled iteration and write a while loop that repeatedly accepts numbers until the user enters -1, then displays their sum.
In sentinel-controlled iteration, a special value called a sentinel indicates that input has ended. The number of repetitions does not need to be known beforehand.
total = 0
number = int(input('Enter a number (-1 to stop): '))
while number != -1:
total += number
number = int(input('Enter a number (-1 to stop): '))
print('Sum:', total)Working:
-1is the sentinel value.- The loop continues while the input is not
-1. - Valid inputs are added to
total. - The sentinel is checked before it can be included in the sum.
A sentinel should normally be a value that cannot be confused with valid input. If negative numbers are valid data, a different termination mechanism may be needed.
Explain the for loop and the range() function in Python. Discuss the roles of the start, stop, and step arguments.
A for loop iterates over the items of an iterable, such as a string, list, tuple, or range.
for item in iterable:
statementThe range() function generates an integer sequence:
range(stop)produces values from0tostop - 1.range(start, stop)begins atstartand excludesstop.range(start, stop, step)changes each value bystep.
Examples:
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 8, 2):
print(i) # 2, 4, 6
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1The step cannot be zero. A negative step is used for descending sequences.
Distinguish between for and while loops in Python. State situations in which each loop is preferable.
Both loops repeat statements, but they express repetition differently.
for loop |
while loop |
|---|---|
| Iterates over an iterable | Repeats while a condition is true |
| Often used when the sequence or count is known | Often used when the iteration count is unknown |
| Advances automatically to the next item | Usually requires an explicit update |
| Less likely to become infinite | Can become infinite if the condition never becomes false |
Use a for loop when:
- Processing every item in a list or string.
- Repeating a fixed number of times.
- Iterating over a
range().
Use a while loop when:
- Waiting until valid input is received.
- Repeating until a sentinel occurs.
- Simulating a process whose stopping time is unknown.
The choice should communicate the intended form of iteration clearly.
Explain the purpose and behavior of break, continue, and the loop else clause in Python.
Python provides statements that alter normal loop execution.
breakimmediately terminates the nearest enclosing loop.continueskips the rest of the current iteration and begins the next iteration.- A loop's
elseclause executes when the loop finishes normally, but it does not execute when the loop is terminated bybreak.
for number in range(2, 10):
if number == 5:
continue
if number == 8:
break
print(number)
else:
print('Loop completed normally')This code skips 5 and terminates at 8; therefore, the else block is not executed.
A common use of loop else is searching: the else block reports failure only when no matching item caused a break.
Write and explain a Python program using nested for loops to print a multiplication table from to .
A nested loop places one loop inside another. For every iteration of the outer loop, the inner loop completes all its iterations.
for row in range(1, 11):
for column in range(1, 11):
product = row * column
print(f'{product:4}', end='')
print()Explanation:
- The outer loop selects each
rowfrom1through10. - For every row, the inner loop selects each
columnfrom1through10. - Each displayed value is .
end=''keeps products on the same line.- The final
print()moves output to the next row.
Since both loops execute times, the multiplication operation is performed times. In general, loops of sizes and perform inner iterations.
Describe the execution of nested while loops. Write a program that prints a right-angled triangular pattern of five rows.
A nested while loop contains one while loop inside another. The inner loop completes its iterations for each iteration of the outer loop.
row = 1
while row <= 5:
column = 1
while column <= row:
print('*', end=' ')
column += 1
print()
row += 1Output:
*
* *
* * *
* * * *
* * * * *The outer loop controls the number of rows. The inner loop prints as many symbols as the current row number. column must be reinitialized to 1 at the start of every outer iteration. Both loop-control variables must be updated to prevent infinite loops.
Compare nested for loops and nested while loops with respect to structure, control, readability, and applications.
Both forms represent multidimensional or repeated iteration, but their control mechanisms differ.
Nested for loops:
- Best when iterating over known ranges or collections.
- Loop-variable progression is handled automatically.
- Usually shorter and easier to read for tables, matrices, and patterns.
Nested while loops:
- Best when repetition depends on conditions that may change unpredictably.
- Require explicit initialization and updating of each control variable.
- Provide more flexible control but have a greater risk of infinite loops.
Examples of applications:
- Nested
for: processing every cell of a matrix or producing a multiplication table. - Nested
while: repeatedly validating grouped input or simulating condition-controlled processes.
For loops with outer size and inner size , the body may run times. If both sizes grow as , the time complexity is commonly .
Write a Python program that simulates rolling two dice repeatedly until their sum is . Explain the use of random numbers and loop termination.
The randint() function can simulate each die because a standard die has integer outcomes from through .
import random
rolls = 0
while True:
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
rolls += 1
print(die1, die2)
if die1 + die2 == 12:
break
print('Number of rolls:', rolls)Explanation:
- Two new random integers are generated during every iteration.
rollsrecords the number of attempts.while Truecreates an indefinite loop.- The loop terminates through
breakwhendie1 + die2 == 12.
Only the outcome gives a sum of . Assuming fair independent dice, its probability on one roll is , although the actual number of iterations varies each time.
Explain how random numbers can be used inside a for loop to estimate the probability of an event. Illustrate with a coin-toss simulation.
Repeated random trials can approximate an event's probability. The ratio of successful outcomes to total trials approaches the theoretical probability as the number of trials becomes large.
import random
trials = 10000
heads = 0
for _ in range(trials):
toss = random.randint(0, 1)
if toss == 1:
heads += 1
estimated_probability = heads / trials
print(estimated_probability)Explanation:
0may represent tails and1may represent heads.- The
forloop conducts exactly10000trials. headscounts successful outcomes.- The estimate is calculated as:
For a fair coin, the result should usually be near , but it will not necessarily be exactly because of random variation.
What is encapsulation in program development? Explain how a repeated conditional or iterative task can be encapsulated in a Python function.
Encapsulation means grouping related logic into a self-contained unit and exposing a clear interface for using it. In Python, functions encapsulate calculations, conditions, and loops behind a meaningful name.
def count_even(numbers):
count = 0
for number in numbers:
if number % 2 == 0:
count += 1
return count
result = count_even([3, 4, 8, 11, 14])The function encapsulates both the loop and the even-number condition.
Benefits:
- Reusability: The same operation can be called with different lists.
- Readability:
count_even()communicates intent clearly. - Maintainability: Changes are made in one location.
- Testing: The function can be tested independently.
- Information hiding: Callers need to know the inputs and result, not every implementation detail.
Define generalization in programming. Show how a specific loop can be generalized using function parameters.
Generalization is the process of replacing fixed values or special-case logic with parameters so that one solution works for a broader class of problems.
A specific loop might print the numbers from 1 to 5:
for number in range(1, 6):
print(number)It can be generalized as follows:
def display_sequence(start, stop, step=1):
for number in range(start, stop, step):
print(number)
display_sequence(1, 6)
display_sequence(10, 0, -2)How it is generalized:
startreplaces a fixed starting value.stopreplaces a fixed boundary.stepcontrols the direction and interval.- A default value keeps common calls concise.
Generalization improves reuse and reduces duplicated code, but parameters should represent meaningful variations rather than making a function unnecessarily complex.
Design a generalized and encapsulated number-guessing game in Python. The program should generate a random number, use a loop, provide conditional feedback, and limit the number of attempts.
The game can be encapsulated in a function and generalized through parameters that define the number range and attempt limit.
import random
def play_guessing_game(low, high, max_attempts):
target = random.randint(low, high)
for attempt in range(1, max_attempts + 1):
guess = int(input(f'Guess a number from {low} to {high}: '))
if guess == target:
print(f'Correct in {attempt} attempts')
return True
elif guess < target:
print('Too low')
else:
print('Too high')
print(f'No attempts left. The number was {target}.')
return False
play_guessing_game(1, 100, 7)Concepts demonstrated:
random.randint(low, high)generates the target.- The
forloop enforces the attempt limit. if-elif-elseprovides feedback.returnends the function immediately after a correct guess.- Encapsulation keeps the complete game logic in one function.
- Parameters generalize the game for different ranges and difficulty levels.
Define the modulus operator in Python. Explain its behavior with suitable examples and mention two practical applications.
The modulus operator % returns the remainder obtained when one number is divided by another.
If is divided by , then:
where is the quotient and is the remainder. In Python, a % b produces .
Examples:
17 % 5evaluates to2.20 % 4evaluates to0.7 % 10evaluates to7.
Applications:
- Checking even or odd numbers: A number
nis even whenn % 2 == 0. - Testing divisibility:
n % d == 0means thatnis divisible byd. - Cyclic operations: The expression
(index + 1) % sizecan wrap an index back to zero.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →