Python Part 4: Control Flow Statements In Python

PYTHON PART 4: CONTROL FLOW STATEMENTS IN PYTHON


Please Subscribe Youtube| Like Facebook | Follow Twitter

Control Flow Statements In Python

In this article, we will provide a detailed overview of control flow statements in Python and provide examples of how they are used in Python programming.

Control flow statements are constructs in programming languages that control the order in which statements are executed. They allow you to perform conditional actions and loop over a set of statements multiple times. Python, a popular high-level programming language, supports several control flow statements that help you control the flow of your programs.

if-else statement

The if-else statement is a conditional statement that allows you to execute certain code based on a particular condition. The if statement checks if a particular condition is true or false, and if it’s true, it executes a set of statements. If the condition is false, the statements inside the else block are executed. Here’s the syntax of an if-else statement in Python:

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

In some cases, you may need to evaluate multiple conditions. In these cases, you can use the elif statement. Here is the syntax for multiple if-else statement:

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

The else if (elif) statement allows you to evaluate multiple conditions and execute different blocks of code based on the result of the evaluations.

Example Code:

score = 75

if score >= 90:
    print("Your grade is A")
elif score >= 80:
    print("Your grade is B")
elif score >= 70:
    print("Your grade is C")
elif score >= 60:
    print("Your grade is D")
else:
    print("Your grade is F")

Output

Your grade is C

In this example, we have assigned a static value of 75 to the variable score. The if-elif-else statement will evaluate the score and print the corresponding grade. Since the score is greater than or equal to 70, the program will print “Your grade is C”.

The pass statement can be used in if-else statements to provide a block of code that does nothing. This can be useful in situations where you want to write a placeholder if-else block, but do not yet know what code you want to execute in each branch.

For example, consider the following code:

if x > 10:
    # do something
else:
    pass

Here, the pass statement is used in the else branch to indicate that no code has been written yet, but the else branch needs to be present for the if-else structure to be syntactically correct.

The pass statement can also be used inside if statements to provide a placeholder block of code that does nothing.

for loop

The for loop is a loop that iterates over a sequence of items, such as a list, tuple, or dictionary. It allows you to perform a set of actions on each item in the sequence. Here’s the syntax of a for loop in Python

for item in sequence:
    # statements to execute for each item

In this syntax, item represents a variable that will be assigned to each item in the sequence, and sequence represents the sequence to iterate over. The code block following the for statement, which is indented, contains the statements that will be executed for each item in the sequence.

During each iteration of the loop, the value of item changes to the next item in the sequence, and the statements in the code block are executed with the new value of item. The loop continues until all items in the sequence have been processed.

Example Code:

For example, the following code demonstrates a for loop that iterates over a list of numbers and prints each number:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

Output

1
2
3
4
5

In this code, the variable numbers is a list of numbers. The for loop iterates over each item in the numbers list and assigns it to the variable num. The print() function then prints the value of num for each iteration of the loop.

When using a for loop to iterate over a sequence in Python, you can access the current index of the loop using the built-in enumerate() function. The enumerate() function takes an iterable (such as a list or a tuple) as its argument and returns a new iterable that produces tuples containing the index and value of each element in the original iterable.

Here’s an example of how to use enumerate() to print out the index and value of each element in a list:

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(index, fruit)

Output

0 apple
1 banana
2 cherry

In this example, fruits is a list of strings. The for loop iterates over the elements in the list, using enumerate() to obtain both the index and the value of each element. The index is stored in the variable index, and the value is stored in the variable fruit. The print() function is then used to print out the index and value of each element.

Break and Continue Statements Inside a For Loop

You can use break and continue statements inside a for loop in Python to modify the flow of the loop.

Here’s an example of how to use break to exit a for loop when a certain condition is met:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        break
    print(num)

Output

1
2

In this example, the for loop iterates over the elements in the numbers list. When the loop encounters the value 3, the break statement is executed, causing the loop to exit early.

Here’s an example of how to use continue to skip over certain elements in a for loop:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        continue
    print(num)

Output

1
2
4
5

In this example, the for loop again iterates over the elements in the numbers list. When the loop encounters the value 3, the continue statement is executed, causing the loop to skip over that element and continue with the next one.

As you can see, using break and continue statements inside a for loop can be a powerful way to modify the flow of the loop and control which elements are processed.

while loop

The while loop is a loop that executes a block of code as long as a particular condition is true. It allows you to perform a set of actions until a certain condition is met. Here’s the syntax of a while loop in Python:

while condition:
    # statements to execute as long as the condition is True

In this syntax, condition represents the condition to be evaluated. The code block following the while statement, which is indented, contains the statements that will be executed as long as the condition is true.

During each iteration of the loop, the condition is checked. If the condition is true, the statements in the code block are executed. This process repeats until the condition becomes false.

Example Code:

For example, the following code demonstrates a while loop that repeatedly prints a message until a counter reaches a certain value.

counter = 0
while counter < 5:
    print("Hello, world!")
    counter += 1

Output

Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!

In this code, the variable counter is initialized to 0. The while loop continues to execute as long as counter is less than 5. The print() function prints the message “Hello, world!” during each iteration of the loop, and the counter variable is incremented by 1. Once counter reaches 5, the condition counter < 5 becomes false and the loop exits.

Conclusion

Control flow statements are a fundamental concept in programming and are essential to making decisions and iterating over sequences of data in Python. In this article, we covered the three primary control flow statements in Python: if-else statements, for loops, while loops.

Python Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

Your email address will not be published. Required fields are marked *