Mastering Control Flow in Python: A Deep Dive into Conditionals, Loops, and Keywords (Detail Explanation)

NIBEDITA (NS)
8 min readJun 3, 2023

Introduction: In the world of programming, control flow refers to the order in which statements are executed. It allows us to dictate the flow of our program, making it more dynamic and responsive to different conditions and inputs.

Python, a versatile and popular programming language, offers powerful control flow mechanisms that enable developers to build complex and efficient applications.

If you didn’t yet complete the previous topics, then it’s highly recommended to finish them first and then jump into it. You can check out the Python series: Python Mastery: Complete Python Guide from Novice to Pro

In this article, we will dive deep into Python’s control flow features, covering conditional statements, loops, and control flow keywords.

1. Conditional Statements

Conditional statements allow us to control the flow of our program based on certain conditions. They help us make decisions and execute different blocks of code depending on whether a condition is true or false.

Condtional statements like if, elif and else in Python.
Photo by Alex Chumak on Unsplash

a) if statement:

The ‘if’ statement is the simplest form of a conditional statement. It executes a block of code if a specified condition is true.

age = 20
if age >= 18:
print("You are eligible to vote.")

# Output: You are eligible to vote.

Here, ‘if’ statement checks if the variable ‘age’ is greater than or equal to 18. If the condition is true, it prints the message "You are eligible to vote." Otherwise, it moves on to the next block of code.

b) else statement:

The ‘else’ statement allows us to specify a block of code that will be executed if the condition in the ‘if’ statement is false.

age = 15
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not yet eligible to vote.")

# Output: You are not yet eligible to vote.

In this case, since the value of ‘age’ is 15 (is less than 18), the ‘if’ condition is false, and the code inside the ‘else’ block is executed. It prints the message "You are not yet eligible to vote."

c) elif statement:

The ‘elif’ statement is used when we want to test multiple conditions. It stands for "else if" and allows us to chain multiple conditions together.

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

# Output: Your grade is B.

In this code snippet, the program evaluates the score and prints the corresponding grade based on the conditions. If the score is 85, the ‘elif’ statement ‘score≥80’ is true, and it prints "Your grade is B."

2. Loops

Loops are used to repeat a block of code multiple times. They allow us to perform iterative tasks and process data more efficiently.

Python Loops (for loops and while loops mainly)
Photo by Boitumelo Phetla on Unsplash

Python provides two main types of loops: ‘for’ loops and ‘while’ loops.

a) for loop:

The ‘for’ loop iterates over a sequence of elements and executes a block of code for each element.

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

# Output
apple
banana
orange

# or if you want it to come in one line with a space-separated, then:
for fruit in fruits:
print(fruit, end=" ")

# Output: apple banana orange
# You can modify according to your needs and fun!😀

In this code snippet, the ‘for’ loop iterates over each element in the ‘fruit’ list and prints it.

b) while loop:

The ‘while’ loop continues executing a block of code as long as a specified condition remains true.

count = 0
while count < 5:
print(count)
count += 1

# Output:
0
1
2
3
4


"""
Here if you won't increments it by 1 (count += 1), then
it will continuously be throwing 0 0 0 0 0... until you stop it.
When you will stop running it'll say "KeyboardInterrupt"
Don't do this, else your system can be crashed too!
"""

In this code snippet, the ‘while’ loop runs until the value of ‘count’ is less than 5. It prints the value of ‘count’ and increments it by 1 in each iteration.

3. Control Flow Keywords

Python provides additional control flow keywords that allow us to modify the behavior of loops and conditional statements.

control flow keywords in Python.
Photo by charlesdeluvio on Unsplash

a) break:

The ‘break’ keyword is used to exit a loop prematurely. When encountered, it immediately terminates the loop and resumes execution at the next statement outside the loop.

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

# Output:
1
2


# But if you will do something like this:
for number in numbers:
if number == -3:
break
print(number)

# output:
1
2
3
4
5

# Modify the code & try yourself, get errors and see how exciting is this!

In this code snippet, the loop will terminate when it encounters the number 3. Take this code, see what it runs, then do changes of your own, it’s okay to get errors, it’s another moment when you solve something of your own after getting errors. You can modify as per your needs & fun! 😀

b) continue:

The ‘continue’ keyword is used to skip the rest of the code within a loop for the current iteration and move to the next iteration.

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

# output:
1
2
4
5

In this code snippet, when the loop reaches the number 3, it skips the ‘print’ statement and moves on to the next iteration.

c) pass:

The ‘pass’ keyword is used as a placeholder when a statement is syntactically required but doesn't need to do anything. It acts as a null operation and allows the code to pass through without any action.

number = 10
if number > 5:
pass
else:
print("Number is less than or equal to 5.")

# Output: It will simply pass the function and won't return anything!

In this code snippet, the ‘pass’ statement is used to indicate that no action is needed when the condition is true. If the number is less than or equal to 5, it executes the ‘print’ statement.

4. Nesting Control Flow Statements

One of the powerful aspects of control flow in Python is the ability to nest control flow statements within each other.

Photo by Luke Chesser on Unsplash

This nesting allows us to create more complex decision-making and looping structures.

grade = 75
if grade >= 60:
if grade >= 90:
print("You achieved an A grade!")
elif grade >= 80:
print("You achieved a B grade!")
else:
print("You achieved a C grade.")
else:
print("You did not pass the exam.")

# Output: You achieved a C grade.

In this code snippet, we have nested ‘if’, ‘elif’, and ‘else’ statements inside the outer ‘if’ statement. Depending on the value of ‘grade’, it will execute the corresponding block of code. This demonstrates the flexibility and expressiveness of control flow in Python.

5. Control Flow in Real-World Applications

Control flow is a fundamental concept that plays a crucial role in various real-world applications.

Photo by Scott Graham on Unsplash

Let’s explore a few scenarios where control flow is commonly used!

a) User Input Validation:

When developing interactive programs, it is essential to validate user input to ensure it meets specific criteria. Control flow allows us to check the validity of user input and prompt them to enter correct information if necessary.

age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to enter.")
else:
print("You are too young to enter.")

# Input: Enter your age: 20
# Output: You are eligible to enter.

# Input: Enter your age: 14
# Output: You are too young to enter.

In this code snippet, the program prompts the user to enter their age. The ‘if’ statement checks if the age is greater than or equal to 18 and displays the appropriate message.

b) Data Filtering and Processing:

Control flow is often used in data filtering and processing tasks. It allows us to iterate over datasets, apply specific conditions, and perform actions based on the results.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_sum = 0
odd_sum = 0
for number in numbers:
if number % 2 == 0:
even_sum += number
else:
odd_sum += number
print("Sum of even numbers:", even_sum)
print("Sum of odd numbers:", odd_sum)

# Output:
Sum of even numbers: 30
Sum of odd numbers: 25

In this code snippet, the ‘for’ loop iterates over each number in the ‘numbers’ list. The ‘if’ statement checks if the number is even or odd and accumulates the sum accordingly. Finally, it prints the sum of even numbers and the sum of odd numbers.

c) Program Flow Control:

Control flow keywords like ‘break’ and ‘continue’ allow us to control the execution flow within loops. They help us optimize our programs and avoid unnecessary iterations.

  • break:
names = ["Nibe", "Dita", "Nibedita", "NS"]
for name in names:
if name == "Nibedita":
break
print(name)

# Output:
Nibe
Dita
  • continue:
names = ["Nibe", "Dita", "Nibedita", "NS"]
for name in names:
if name == "Nibedita":
continue
print(name)

# Output:
Nibe
Dita
NS

Conclusion: Control flow is a fundamental concept in programming, and Python provides a rich set of features to handle it effectively. In this article, we explored conditional statements, including ‘if’, ‘else’, and ‘elif’, which allow us to make decisions based on conditions. We also discussed loops, such as ‘for’ and ‘while’, which enable us to iterate over sequences and repeat blocks of code.

If you want a clear overview of “complete Python”, one type of the whole Python syllabus; then you can have a look:

Additionally, we examined control flow keywords like ‘break’, ‘continue’, and ‘pass’, which provide additional control and flexibility within loops and conditional statements.

Photo by Clément Hélardot on Unsplash

With a solid understanding of control flow in Python, you can create dynamic and efficient programs that respond to various conditions and input. So, keep practicing and exploring the possibilities of control flow, and you’ll be well-equipped to write robust and adaptable code.

If you want to become a Data Scientist, then you may be interested in:

Happy Exploring! 🙂

--

--

NIBEDITA (NS)
NIBEDITA (NS)

Written by NIBEDITA (NS)

Tech enthusiast, Content Writer and lifelong learner! Sharing insights on the latest trends, innovation, and technology's impact on our world.

No responses yet