Flow Control in Python: A Complete Guide to Conditional Logic and Loops

Flow control in programming decides the order in which instructions run. It helps manage how a program makes choices and repeats tasks using conditions (like if statements) and loops (like for or while). This allows programs to make decisions and perform repetitive actions effectively.

Why flow control?

  • To understand statement execution: It determines how and when different parts of a program run, which is essential for functional and efficient code.
  • Execution modes:
    1. Sequential: Statements run in the order they appear.
    2. Conditional: Statements run based on specific conditions.
    3. Looping: Statements run repeatedly based on conditions or sequences.
Python Flow Control: Conditional Statements and Loops
Python Flow Control: Conditional Statements and Loops

Sequential Execution:

Statements are executed one after another sequentially in the order they appear consecutively

Example:

print("Step 1")
print("Step 2")
print("Step 3")

Conditional Execution:

Statements are executed conditionally based on whether a specified condition is met.

Possible combinations:

  • if
  • if else
  • if elif else
  • if elif elif …. else

Examples:

if :

x = 10
if x > 5:
    print("x is greater than 5")

#Output:
x is greater than 5

if-else:

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than 5")

#Output:
x is less than 5

if-elif-else:

x = 7
if x > 10:
    print("x is greater than 10")
elif x > 5:
    print("x is greater than 5 but less than or equal to 10")
else:
    print("x is 5 or less")

#Output:
x is greater than 5 but less than or equal to 10

if-elif-elif-else:

x = 15
if x > 20:
    print("x is greater than 20")
elif x > 15:
    print("x is greater than 15 but less than or equal to 20")
elif x > 10:
    print("x is greater than 10 but less than or equal to 15")
else:
    print("x is 10 or less")

#Output:
x is greater than 10 but less than or equal to 15

nested if-elif-else:

number = 7
if number > 0:
    print("The number is positive.")
    if number % 2 == 0:
        print("The number is even.")
    else:
        print("The number is odd.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")

#Output:
The number is positive.
The number is odd.

Looping statements:

Looping statements enable the repetitive execution of a block of code while a condition holds true or for iterating over a sequence. In Python, the primary types of loops are the for loop and the while loop

  • for loop
  • while loop

for loop:

It is used to iterate and perform an action on every element in a sequence of data types, such as a list, tuple, or string.

Syntax:

# Single Loop
for variable in sequence:
 	# Block of code to execute
# Nested For Loop
for variable in sequence:
    # Block of code to execute
	for var_2 in sequence:
		# Block of code to execute

Examples:

1. Single for loop:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

# Output:
apple
banana
cherry

2. Nested for loop:

for i in range(3):  # Outer loop
    for j in range(2):  # Inner loop
        print(f"Outer loop iteration {i}, Inner loop iteration {j}")

# Output:
Outer loop iteration 0, Inner loop iteration 0
Outer loop iteration 0, Inner loop iteration 1
Outer loop iteration 1, Inner loop iteration 0
Outer loop iteration 1, Inner loop iteration 1
Outer loop iteration 2, Inner loop iteration 0
Outer loop iteration 2, Inner loop iteration 1

While loop

We should use a while loop to execute a group of statements recursively until a condition becomes False.

Syntax:

initialization
while condition:
 	while block statements
  	increment/decrement
  • A while loop requires a condition followed by a colon (:); not using the colon results in a syntax error.
  • Proper indentation after the loop is mandatory, and the condition must evaluate to a boolean (True or False).
image 2 Explore and Read Our Blogs Written By Our Insutry Experts Learn From KSR Data Vizon

Main Parts of a While Loop:

  1. Initialization: The variable is initialized before entering the loop (like count=0)
  2. Condition: The loop checks the condition at the start of each iteration. If True, the loop executes; if False, it terminates and moves to the next line of code.
  3. Increment/Decrement: The value is updated using an arithmetic operator to ensure progress toward meeting the exit condition.

Explanation:

  • The loop starts by checking the condition with the initialized value.
  • If the condition is True, the loop’s statements are executed.
  • After each iteration, the variable is incremented or decremented, and the condition is rechecked for the next iteration.
  • The loop continues until the condition becomes False.

Example 1:

# Initialization
count = 1

# While loop with condition
while count <= 5:
    print(f"Iteration {count}")
    # Increment section
    count += 1

# Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Example 2:

# Initialization for outer loop
i = 1
while i <= 3: # Outer while loop
    j = 1  # Initialization for inner loop
    while j <= 2:     # Inner while loop
        print(f"Outer loop iteration {i}, Inner loop iteration {j}")
        j += 1  # Increment for inner loop
    i += 1  # Increment for outer loop

# Output
Outer loop iteration 1, Inner loop iteration 1
Outer loop iteration 1, Inner loop iteration 2
Outer loop iteration 2, Inner loop iteration 1
Outer loop iteration 2, Inner loop iteration 2
Outer loop iteration 3, Inner loop iteration 1
Outer loop iteration 3, Inner loop iteration 2

Infinite while loops:

  • The loop that never ends is called an infinite group (when a condition is always true).
  • To come out of the infinite loop we need to press ctrl + c

Example:

while True:
     print("Hello")

# Output:
Hello
Hello
Hello
.
.

Control Flow Statements

Control flow statements in loops manage the execution by altering the standard flow, such as breaking out of loops or skipping certain iterations. In Python, the primary control flow statements used in loops are:

  1. break
  2. continue
  3. pass
  4. else

break statement:

Exits the loop immediately when a specific condition is met and doesn’t do the remaining iterations.

Example:

# Example of a for loop
for i in range(5): 
    if i == 3:
        break  # Exit the loop when i equals 3
    print(i)

# Output:
0
1
2

continue statement:

It skips the current iteration and moves to the next one, allowing the loop to continue executing.

Example:

# Example of a for loop
for i in range(5):
    if i == 2:
        continue  # Skip the iteration when i equals 2
    print(i)

# Output:
0
1
3
4

pass statement:

Does nothing and acts as a placeholder in the loop. Useful when the loop requires a statement syntactically, but no action is needed at that point.

Example:

# Example of a for loop
for i in range(5):
    if i == 3:
        pass  # No operation, just a placeholder
    print(i)

# Output:
0
1
2
3
4

else with Loops:

Executes after the loop finishes all its iterations unless a break statement is encountered.

Example:

# Example of a for loop
for i in range(5):
    print(i)
else:
    print("Loop completed")

# Output:
0
1
2
3
4
Loop completed

Conclusion

Flow control mechanisms in Python, including conditional statements, loops, and control flow statements, are the main ones that direct the execution of programs. They help to manage decision-making and repetitive tasks, enabling dynamic and efficient code execution.

Knowledge Check

Related Article No.4

Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizon
► KSR Datavizon Instagram :- https://www.instagram.com/ksr_datavision
► KSR Datavizon Face book :- https://www.facebook.com/KSRConsultingServices
► KSR Datavizon Playstore :- https://play.google.com/store/apps/details?id=com.datavizon.courses&hl=en-IN
► KSR Datavizon Appstore :- https://apps.apple.com/in/app/ksr-datavizon/id1611034268

Related Posts

Leave a Reply

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