Shopping cart

Subtotal:

$0.00

PCEP-30-02 Control Flow - Conditional Blocks and Loops

Control Flow - Conditional Blocks and Loops

Detailed list of PCEP-30-02 knowledge points

Control Flow - Conditional Blocks and Loops Detailed Explanation

1. Conditional Statements

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.

1.1 If Statement

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:

  • The condition x > 5 is evaluated.
  • If the condition is 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")
1.2 If-Else Statement

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:

  • If x > 5 evaluates to True, the first block runs.
  • If 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")
1.3 If-Elif-Else Statement

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:

  • The program checks each condition in sequence.
  • If a condition is 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")
1.4 Nested Conditions

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:

  • First, x > 5 is checked.
  • If 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")

2. Loops

Loops allow you to repeat a block of code multiple times. Python supports two types of loops: for and while.

2.1 For Loop

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:

  • The loop goes through each item in the sequence (fruits).
  • On each iteration, the variable 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)
2.2 While Loop

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:

  • The loop checks the condition x < 5.
  • If True, the block runs, and x is incremented.
  • The loop stops when 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}")

3. Loop Control Statements

Control statements modify the flow of loops.

3.1 Break

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
3.2 Continue

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
3.3 Else in Loops

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

Control Flow - Conditional Blocks and Loops (Additional Content)

1. The else Clause with a while Loop

In 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.

Example: while with else

x = 0
while x < 3:
    print(x)
    x += 1
else:
    print("While loop completed")

Output:

0  
1  
2  
While loop completed

Explanation:

  • 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.

With 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.

2. The pass Statement

The 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.

Syntax:

if condition:
    pass  # Do nothing

Example:

x = 10
if x > 0:
    pass  # Placeholder for future logic
print("Program continues...")

Explanation:

  • In situations where you're required to have a statement (e.g., after 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.

3. while True and break: Simulating Indefinite Loops

This 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.

Pattern:

while True:
    user_input = input("Enter something (or 'exit' to quit): ")
    if user_input == "exit":
        break
    print(f"You entered: {user_input}")

Explanation:

  • 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.

Summary Table

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

Frequently Asked Questions

Why does my while loop become infinite even when I expect it to stop?

Answer:

A while loop becomes infinite when its condition never evaluates to False.

Explanation:

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?

Answer:

A for loop is used for iterating over sequences, while a while loop runs based on a condition.

Explanation:

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?

Answer:

elif blocks only execute if all previous conditions in the if-elif chain are False.

Explanation:

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?

Answer:

The break statement immediately terminates the loop and exits its block.

Explanation:

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?

Answer:

The continue statement skips the current iteration and proceeds to the next loop cycle.

Explanation:

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

PCEP-30-02 Training Course
$68$29.99
PCEP-30-02 Training Course