Control Flow Statements in Python

Control flow statements are essential in programming as they determine the order in which instructions are executed. In Python, control flow is managed through sequential, decision, and loop control flow statements. Understanding these is key to writing effective and efficient code.

Control Flow Statement

Sequential Control Flow Statements - Sequential control flow is the default mode of execution in Python, where statements are executed one after another in the order they appear.

Decision Control Flow Statements - Decision control flow statements allow your program to choose different paths of execution based on conditions. The primary decision control statements in Python are if, elif, and else.

Loop Control Flow Statements - Loop control flow statements are used to execute a block of code multiple times. Python supports two main types of loops: for and while.

Decision Control Flow Statements in Python

Decision control flow statements in Python allow you to make choices in your code, executing different blocks of code based on conditions. The primary decision control flow statements are if, if...else, if...elif...else, and nested if statements. Let's delve into each type of decision control flow statement in detail.

if Statement

The if statement is the most basic form of decision-making in Python. It evaluates a condition (an expression that returns a boolean value, either True or False). If the condition evaluates to True, the block of code within the if statement is executed. If the condition is False, the code block is skipped.

Syntax:

if condition:
    # code to execute if condition is True

Example:

temperature = 35
if temperature > 30:
    print("It's a hot day!")

In this example, if temperature is greater than 30, the message "It's a hot day!" is printed.

if...else Statement

The if...else statement provides an alternative path of execution. If the if condition evaluates to False, the code inside the else block is executed.

Syntax:

if condition:
    # code to execute if condition is True
else:
    # code to execute if condition is False

Example:

age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

In this example, if age is 18 or older, "You are an adult." is printed. Otherwise, "You are a minor." is printed.

if...elif...else Statement

The if...elif...else statement allows for multiple conditions to be evaluated sequentially. Each elif (short for "else if") block is checked only if all previous conditions were False. The else block executes if none of the preceding conditions are True.

Syntax:

if condition1:
    # code to execute if condition1 is True
elif condition2:
    # code to execute if condition2 is True
else:
    # code to execute if none of the above conditions are True

Example:

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D")

In this example, the program checks the score and prints Grade: B.

Nested if Statements

Nested if statements are if statements placed inside another if statement. This allows for more complex conditions to be evaluated.

Syntax:

if condition1:
    if condition2:
        # code to execute if both condition1 and condition2 are True
    else:
        # code to execute if condition1 is True and condition2 is False
else:
    # code to execute if condition1 is False

Example:

age = 25
has_ticket = True
 
if age >= 18:
    if has_ticket:
        print("You can enter the movie theater.")
    else:
        print("You need a ticket to enter.")
else:
    print("You are not old enough to enter.")

In this example, the program first checks if age is 18 or older. If true, it then checks if has_ticket is True. Depending on these conditions, appropriate messages are printed. Here it will print "You can enter the movie theater".

Loop Control Flow Statements in Python

Loop control flow statements in Python allow you to execute a block of code repeatedly. This repetition can be controlled in several ways using while loops, for loops, and by utilizing continue and break statements to manage the flow within loops.

The while Loop

The while loop repeatedly executes a block of code as long as a specified condition evaluates to True. It is commonly used when the number of iterations is not known before the loop starts.

Syntax:

while condition:
    # Code to execute as long as condition is True
    # Update condition variables to eventually end the loop

Explanation:

  • condition: An expression that is evaluated before each iteration. If it evaluates to True, the loop body is executed. If it evaluates to False, the loop terminates.
  • The loop body should include code that modifies the condition or otherwise influences when the loop should end to avoid infinite loops.

Example:

count = 0
while count < 5:
    print("Count is:", count)
    count += 1

Output:

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4

In this example, the loop will continue to execute as long as count is less than 5. With each iteration, count is incremented by 1, eventually making the condition False and terminating the loop.

The for Loop

The for loop is used to iterate over a sequence (such as a list, tuple, dictionary, string, or range) or other iterable objects. It is typically used when the number of iterations is known or can be easily determined.

Syntax:

for variable in sequence:
    # Code to execute for each item in sequence

Explanation:

  • variable: A name that takes on the value of each item in the sequence on each iteration.
  • sequence: An iterable object that is being iterated over. This could be a list, tuple, string, or any object that supports iteration.

Example:

for i in range(5):
    print("i is:", i)

Output:

i is: 0
i is: 1
i is: 2
i is: 3
i is: 4

In this example, range(5) generates numbers from 0 to 4. The for loop iterates over these numbers, and each number is printed.

The continue Statement

The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. When continue is executed, the remaining code in the loop body is skipped for the current iteration.

Syntax:

for variable in sequence:
    if condition:
        continue
    # Code to execute if condition is False

Example:

for i in range(10):
    if i % 2 == 0:
        continue
    print("Odd number:", i)

Output:

Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9

In this example, the continue statement skips the print statement for even numbers, resulting in only odd numbers being printed.

The break Statement

The break statement is used to exit a loop prematurely. When break is executed, the loop is terminated, and the program control moves to the first statement after the loop.

Syntax:

for variable in sequence:
    if condition:
        break
    # Code to execute if condition is False

Example:

for i in range(10):
    if i == 5:
        break
    print("i is:", i)

Output:

i is: 0
i is: 1
i is: 2
i is: 3
i is: 4

In this example, the loop will terminate when i equals 5. Therefore, only numbers from 0 to 4 are printed before the loop exits.

Combining continue and break Statements

You can use continue and break statements together within the same loop to control the flow more precisely.

Example:

for i in range(10):
    if i % 2 == 0:
        continue
    if i == 7:
        break
    print("Odd number less than 7:", i)

Output:

Odd number less than 7: 1
Odd number less than 7: 3
Odd number less than 7: 5

In this example:

  • continue skips even numbers.
  • break exits the loop when i equals 7.
  • Numbers 1, 3, and 5 are printed before the loop terminates.
How's article quality?

Last updated on -

Page Contents