Conditional statements allow your program to make decisions based on certain conditions. This is achieved using the if, if-else, and if-elif-else constructs.
The if statement is the simplest form of a conditional. It checks a condition and executes the code block only if the condition is True.
Syntax:
if condition:
# code block (executed if condition is True)
Example:
x = 10
if x > 5:
print("x is greater than 5")
Explanation:
x > 5 is evaluated.True, the indented code block will run.More Examples:
#Check if a number is positive
number = 7
if number > 0:
print("The number is positive")
The if-else statement provides an alternative block of code to execute if the condition is False.
Syntax:
if condition:
# code block (executed if condition is True)
else:
# alternative code block (executed if condition is False)
Example:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
Explanation:
x > 5 evaluates to True, the first block runs.x > 5 evaluates to False, the else block runs.More Examples:
#Check if a number is even or odd
number = 4
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
When there are multiple conditions to check, use if-elif-else. It allows you to test several conditions in order, executing the first block with a True condition.
Syntax:
if condition1:
# code block (executed if condition1 is True)
elif condition2:
# code block (executed if condition1 is False and condition2 is True)
else:
# alternative code block (executed if all conditions are False)
Example:
x = 10
if x > 15:
print("x is greater than 15")
elif x > 5:
print("x is greater than 5 but not greater than 15")
else:
print("x is 5 or less")
Explanation:
True, its block runs, and the rest are skipped.More Examples:
#Grading system based on score
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Conditions can be nested inside each other to check multiple levels of logic.
Syntax:
if condition1:
if condition2:
# nested block (executed if condition1 and condition2 are True)
Example:
x = 10
if x > 5:
if x % 2 == 0:
print("x is greater than 5 and even")
Explanation:
x > 5 is checked.True, the nested condition x % 2 == 0 is checked.More Examples:
#Check if a number is positive and even
number = 12
if number > 0:
if number % 2 == 0:
print("The number is positive and even")
else:
print("The number is positive but odd")
else:
print("The number is not positive")
Loops allow you to repeat a block of code multiple times. Python supports two types of loops: for and while.
The for loop iterates over a sequence (like a list, string, or range).
Syntax:
for item in sequence:
# code block (executed for each item in the sequence)
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Explanation:
fruits).fruit holds the current item.More Examples:
#Print numbers from 0 to 4
for i in range(5): # range(5) generates 0, 1, 2, 3, 4
print(i)
The while loop repeats a block of code as long as the condition is True.
Syntax:
while condition:
# code block (executed while condition is True)
Example:
x = 0
while x < 5:
print(x)
x += 1 # Increment x to avoid an infinite loop
Explanation:
x < 5.True, the block runs, and x is incremented.x < 5 becomes False.More Examples:
#Print numbers until the user enters "stop"
while True:
user_input = input("Enter a number (or 'stop' to quit): ")
if user_input == "stop":
break
print(f"You entered: {user_input}")
Control statements modify the flow of loops.
The break statement exits the nearest enclosing loop immediately.
Example:
for i in range(10):
if i == 5:
break # Exit the loop when i equals 5
print(i)
Output:
0
1
2
3
4
The continue statement skips the rest of the code in the current iteration and moves to the next iteration.
Example:
for i in range(5):
if i == 3:
continue # Skip the iteration when i equals 3
print(i)
Output:
0
1
2
4
The else block in a loop runs if the loop is not terminated by a break.
Example:
for i in range(3):
print(i)
else:
print("Loop completed!")
Output:
0
1
2
Loop completed!
Example with break:
for i in range(3):
if i == 2:
break
print(i)
else:
print("Loop completed!") # This won't execute
Output:
0
1
else Clause with a while LoopIn Python, the else block can be used with both for and while loops. The else clause executes only if the loop completes normally, that is, without hitting a break statement.
While many learners see it used with for loops, it works the same way with while loops.
while with elsex = 0
while x < 3:
print(x)
x += 1
else:
print("While loop completed")
Output:
0
1
2
While loop completed
The loop runs while x < 3.
After x reaches 3, the condition becomes false.
Since the loop was not interrupted by a break, the else block runs.
break inside the loop:x = 0
while x < 5:
if x == 3:
break
print(x)
x += 1
else:
print("This will NOT be printed")
Output:
0
1
2
In this case, the else block is skipped because the loop was terminated with break.
pass StatementThe pass statement in Python is used as a placeholder. It does nothing when executed, but is syntactically required when a statement is needed, such as in an if, for, while, or function body.
if condition:
pass # Do nothing
x = 10
if x > 0:
pass # Placeholder for future logic
print("Program continues...")
Explanation:
if, for, etc.) but haven't implemented logic yet, pass keeps the code syntactically valid.This is especially common in:
Empty function definitions during development
Class method placeholders
Branches in control flow yet to be implemented
Important for PCEP:
PCEP might include a question with this option to test if you understand that pass is valid and does not produce an error.
while True and break: Simulating Indefinite LoopsThis is a very common pattern in Python to simulate an indefinite loop that continues until a specific condition is met. It often replaces the traditional do-while loop found in other languages.
while True:
user_input = input("Enter something (or 'exit' to quit): ")
if user_input == "exit":
break
print(f"You entered: {user_input}")
while True creates an infinite loop.
The loop continues endlessly unless a break statement is encountered.
It's useful when the termination condition depends on user input or runtime behavior, not something easily written in a while condition.
| Feature | Syntax | Purpose |
|---|---|---|
while ... else |
while condition: ... else: |
Executes else only if the loop is not broken |
pass |
if x > 0: pass |
Does nothing, used as a placeholder |
while True + break |
while True: if condition: break |
Infinite loop with manual termination |
Why does my while loop become infinite even when I expect it to stop?
A while loop becomes infinite when its condition never evaluates to False.
This typically occurs when the loop control variable is not updated correctly inside the loop. For example, forgetting to increment a counter prevents the condition from changing. Another issue is incorrect condition logic, such as using the wrong comparison operator. Infinite loops can freeze programs and must be carefully controlled. Ensuring proper updates and verifying exit conditions prevents this issue.
Demand Score: 88
Exam Relevance Score: 92
What is the difference between for and while loops in Python?
A for loop is used for iterating over sequences, while a while loop runs based on a condition.
For loops are typically used when the number of iterations is known or when iterating over collections like lists or strings. While loops are better suited for situations where repetition depends on a condition. A common mistake is using while loops when a for loop would be simpler and safer, increasing the risk of infinite loops.
Demand Score: 82
Exam Relevance Score: 90
Why is my elif condition not executing even when it seems true?
elif blocks only execute if all previous conditions in the if-elif chain are False.
If an earlier if condition evaluates to True, Python skips all subsequent elif blocks. This often leads to confusion when conditions overlap. Proper ordering of conditions is crucial. A common mistake is placing broader conditions before more specific ones, preventing expected branches from executing.
Demand Score: 80
Exam Relevance Score: 88
How does the break statement affect loop execution?
The break statement immediately terminates the loop and exits its block.
When break is executed, the loop stops regardless of the condition. It is commonly used when a specific condition is met inside the loop. A common mistake is placing break incorrectly, causing premature termination or making parts of the loop unreachable.
Demand Score: 78
Exam Relevance Score: 87
What does the continue statement do in Python loops?
The continue statement skips the current iteration and proceeds to the next loop cycle.
Instead of terminating the loop, continue ignores the remaining code in the current iteration. This is useful for filtering conditions. A common mistake is misunderstanding that continue does not stop the loop entirely, which can lead to unexpected repeated behavior.
Demand Score: 76
Exam Relevance Score: 85