Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Understanding What Are Control Flow Statements in Python

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

Python control statements are essential as they direct the flow of a program. They enable you to make choices, perform repetitive tasks, and manage how a code block is executed based on specific factors. These structures help you build dynamic and flexible programs that behave differently when presented with different inputs or under different circumstances.

 

This blog post will introduce various Python control statements including conditional statements like ‘if’, ‘if-else’, ‘if-elif-else’, and loop control statements such as ‘for’ and ‘while’. It will also discuss control flow altering statements like ‘break’, ‘continue’, and ‘pass’ in programming.

What are Control Statements in Python?

Control Statements in Python are instructions that govern how a program should operate. Such decisions may include making certain actions repeatedly or at times executing particular codes depending on given requirements.

 

Control statements can be categorised into three main types:

 

  • Conditional statements
  • Loop statements
  • Control flow-altering statements

 

We will cover each of these in-depth.

Conditional Control Statements in Python

Conditions can be demonstrated using ‘if’, ‘if-else’, and ‘if-elif-else’ statements which allow a program to execute different blocks of code based on some criteria.

The if statement

In the Python programming language, there is an easy way to execute certain code-blocks only at the time when the condition is true using the “if” statement. It’s one of the simplest yet most commonly used types of control statements. If the expression is ‘true’ then execute the block inside the “if” else it will be skipped implicitly.

 

For making decisions within your program, use an ‘if’ statement’. For example, before granting access to a system you want to verify whether or not someone has entered the right password.

 

Example

Let’s consider a simple example where we check if a number is positive.

 

The if statement checks if the value of the number is greater than 0 (number > 0). Since the condition number > 0 is true (10 is greater than 0), the code inside the if block is executed, and “The number is positive.” is printed to the console.

# Define a number number = 10  # Check if the number is positive if number > 0: print("The number is positive.")

Output:

The number is positive.

The if-else statement

The if-else statement allows you to execute one block of code if a condition is true and another block of code if the condition is false. This is useful when you need to choose between two alternatives.

 

Example

In this example, we check if a number is even or odd.

  • Condition: Check if a number is even or odd.
  • If block: Execute if the number is even.
  • Else block: Execute if the number is odd.

 

# Define a number number = 7  # Check if the number is even if number % 2 == 0: print("The number is even.") else: print("The number is odd.")

Output:

The number is odd.

The nested-if statement

A nested if statement is an if statement inside another if statement. It allows you to check multiple conditions by placing one if statement inside another.

 

Example

In this example, we check if a number is positive and then whether it is even or odd.

 

  • Outer Condition: Check if a number is positive.
    • Inner Condition: If positive, check if the number is even.
    • Else Block of Inner Condition: If positive but not even, the number is odd.

 

  • Else Block of Outer Condition: If not positive, the number is non-positive.

 

# Define a number number = 12  # Check if the number is positive if number > 0: print("The number is positive.")  # Check if the positive number is even if number % 2 == 0: print("The number is even.") else: print("The number is odd.") else: print("The number is not positive.")

Output:

The number is positive. The number is even.

The if-elif-else chain

The if-elif-else chain is used when you have multiple conditions to check. It allows you to execute different blocks of code based on which condition is true. The elif stands for “else if” and can be used multiple times.

 

Example

In this example, we check if a number is positive, zero, or negative.

 

  • First Condition: Check if a number is positive.
  • Elif Condition: Check if the number is zero.
  • Else Block: Execute if the number is negative.

 

# Define a number number = 0  # Check if the number is positive if number > 0: print("The number is positive.") elif number == 0: print("The number is zero.") else: print("The number is negative.")

Output:

The number is zero.

Short Hand if-else statement in Python

The short-hand if-else statement, also known as the ternary operator, allows you to write an if-else statement in a single line. This is useful for simple conditions where you want to make your code more concise.

 

Example

In this example, we check if a user is an admin and assign a message accordingly.

# Define a user role user_role = "admin"  # Assign message using short-hand if-else statement message = "Access granted" if user_role == "admin" else "Access denied" print(message)

Output:

Access granted

Short Hand if statement in Python

The short-hand if statement allows you to write a simple if statement in one line. This is useful for very simple conditions where you only need to perform one action.

 

Example

In this example, we check if a user is logged in and print a welcome message if true.

 

# Define a user login status is_logged_in = True # Print welcome message using short-hand if statement if is_logged_in: print("Welcome back!")

Output:

Welcome back!

The Match Case Statement

The match case statement, introduced in Python 3.10, is similar to switch-case statements in other languages. It allows you to match a variable against multiple values and execute the corresponding code block. This can make your code more readable and organised, especially when dealing with multiple possible values of a variable.

 

Example

In this example, we match the user’s choice against different cases to determine the action to perform.

# Define a user choice user_choice = "B"  # Match case statement match user_choice: case "A": print("You selected option A.") case "B": print("You selected option B.") case "C": print("You selected option C.") case _: print("Invalid choice.")

Output:

You selected option B.

Loop Control Statements in Python

Loop statements, such as for and while, allow the program to repeat a block of code multiple times.

For Loop

The for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) and execute a block of code for each item in the sequence. It is a convenient way to loop through elements without needing an index counter.

 

  • Use Case: Print each item in a shopping list.

 

Example

In this example, we have a list called shopping_list that contains various items. We use a for loop to iterate over each item in the list and print it. This helps us to easily access and print each element without manually using an index.

# Define a shopping list shopping_list = ["milk", "bread", "eggs", "fruits"]   # Iterate over each item in the list and print it for item in shopping_list: print(item)

Output:

milk bread eggs fruits

While Loop

The while loop in Python repeatedly executes a block of code as long as a given condition is true. It is useful for situations where the number of iterations is not known beforehand.

 

  • Use Case: Print numbers from 1 to 5.

 

Example

In this example, we start with a variable number set to 1. We use a while loop to print the value of a number as long as it is less than or equal to 5. After each iteration, we increase the value of the number by 1. This loop will continue until the number exceeds 5.

# Initialise the number number = 1  # Loop while the number is less than or equal to 5 while number <= 5: print(number) number += 1  # Increment the number

Output:

1 2 3 4 5

Nested Loop

A nested loop is a loop inside another loop. The inner loop runs completely every time the outer loop runs once. This is useful for working with multi-dimensional data structures like matrices.

 

  • Use Case: Print elements of a 2D list (matrix).

 

Example

In this example, we have a 2D list (matrix) called matrix. The outer loop iterates over each row in the matrix. The inner loop iterates over each element within the current row. We print each element followed by a space, and after finishing a row, we print a newline to format the output properly.

# Define a 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Iterate over each row in the matrix for row in matrix: # Iterate over each element in the row for element in row: print(element, end=" ") print()  # Newline after each row

Output:

1 2 3 4 5 6 7 8 9

List Comprehensions

List comprehensions provide a concise way to create lists in Python. They are used to create new lists by applying an expression to each element in an existing list or any other iterable. This makes the code more readable and compact.

 

  • Use Case: Create a list of squares of numbers from 1 to 10.

 

Example

In this example, we use list comprehension to generate a list of squares of numbers from 1 to 10. The expression x**2 calculates the square of each number x in the range from 1 to 10. The resulting list of squares is then printed.

# Use list comprehension to create a list of squares squares = [x**2 for x in range(1, 11)] print(squares)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Control Flow Altering Statements

Control flow altering statements like a ‘break’, ‘continue’, and ‘pass’ manage the execution within loops or conditional statements. Understanding and using these control statements effectively is key to writing efficient and readable Python code.

Break Statement

The break statement in Python is used to exit a loop prematurely when a certain condition is met. It allows you to stop the loop and continue with the next part of the code outside the loop.

 

  • Use Case: Search for an item in a list and stop the search once the item is found.

 

Example

In this example, we have a list of items and we want to find a specific item, “eggs”. We use a for loop to iterate through the list. When we find “eggs”, we use the break statement to exit the loop immediately, stopping any further iteration.

# Define a list of items items = ["milk", "bread", "eggs", "fruits"]  # Define the item to search for item_to_find = "eggs"  # Iterate over each item in the list for item in items: if item == item_to_find: print(f"{item_to_find} found!") break  # Exit the loop once the item is found

Output:

eggs found!

Continue Statement

The continue statement in Python is used to skip the current iteration of a loop and continue with the next iteration. This is useful when you want to skip certain items in a loop based on a condition.

 

  • Use Case: Print all even numbers from a list, skipping odd numbers.

 

Example

In this example, we have a list of numbers and we want to print only the even numbers. We use a for loop to iterate through the list. If the current number is odd, we use the continue statement to skip the rest of the loop and move to the next iteration.

# Define a list of numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Iterate over each number in the list for number in numbers: if number % 2 != 0: continue  # Skip odd numbers print(number)

Output:

2 4 6 8 10

Pass Statement

The pass statement in Python is a null statement that does nothing when executed. It is used as a placeholder in situations where a statement is syntactically required but you do not want to execute any code.

 

  • Use Case: Define a function or loop that you plan to implement later without causing a syntax error.

 

Example

In this example, we define a function future_function that we plan to implement later. We use the pass statement as a placeholder to ensure the function definition is syntactically correct, even though it currently does nothing.

# Define a function that will be implemented later def future_function(): pass  # Placeholder for future implementation  # Define a loop with a pass statement for i in range(5): pass  # Placeholder for future implementation

Output:

(No output, but the code runs without errors)

Why are Control Statements Important in Python?

In Python, control statements are important as they determine program execution flow, making code dynamic and responsive.

 

  • Decision Making: Control statements such as if, if-else, and elif-else-if besides others allow for conditional decisions in programs.
  • Looping: While and For loops, among others, repeatedly execute codes until a specific condition is reached.
  • Code Simplification: Break, continue, and pass are some of the control flow-altering statements that make complex logic simple hence improving readability.
  • Performance Optimization: With control statements, it becomes possible to only execute essential codes thereby optimising performance and resource utilisation by avoiding unnecessary executions which may affect system speed.
  • Adaptability: They help us deal with diverse conditions or inputs thereby making our programs more flexible and strong.

Conclusion

Python’s control statements are used by programmers to effectively steer their programming. These would enable you to write effective codes that are efficient, readable, and responsive to varying situations when applied properly. Whether it involves making decisions using ‘if’, looping around ‘while’ or ‘for’, breaking away from a line of code, or proceeding on ‘break’ or ‘continue’, all these are vital for solid coding. Gaining mastery over control statements helps one handle various scenarios and inputs, thus enhancing adaptability in their programs.

FAQs
Control statements manage the flow of a program based on conditions and loops.
The if statement executes a block of code if a specified condition is true.
A for loop iterates over a sequence, executing a block of code for each item.
Use a while loop when you need to repeat a block of code as long as a condition is true.
The break statement exits the loop immediately when a specific condition is met.
The continue statement skips the rest of the current loop iteration and moves to the next one.
The pass statement is a placeholder that does nothing; it’s used where a statement is required syntactically.
A nested loop is a loop inside another loop, used for multi-dimensional data structures.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved