Flow Controls in Python

Flow controls are also referred as flow control structures. Flow controls are fundamental concepts in programming languages. Generally flow controls are used to control the flow of program execution or to provide the direction that program needs to follow. Flow controls decides the order in which individual statements, instructions, or function calls to be executed or evaluated. In other words, they manage and control the flow of a program’s execution based on conditions, iterations, or exceptions.

Flow Controls in Python

Flow control in Python refers to the mechanisms that allow you to control the order in which statements are executed, based on certain conditions or repetitions. These controls allow programs to make decisions, repeat actions, or handle errors in a structured way. Python provides several structures for flow control.

Conditional Statements – if, elif, else, nested if-else

Conditional statements in Python allow you to execute certain blocks of code based on whether a condition is True or False. These conditional statements are fundamental to control the flow of program execution. It enables decision-making within the code and helps to take different actions based on the conditions. if, if-else, if-elif-else are main conditional statements provided in Python.

if statement

if condition flowchart
if condition flowchart
  • if statement is used to test a condition.
  • If the condition evaluates to True, the code block within the if statement is executed.
if condition:
    # block of code to execute if the condition is true
number = 32
if number >= 20:
    print("Number is greater than 20.")

From the example, given number is 32 and the condition number >= 20 evaluates to True, so it will print “Number is greater than 20”.

if-else statement

if-else condition flowchart
if-else condition flowchart
  • if-else statement allows you to define an alternative else block of code.
  • else block of code to be executed if the condition in the if statement is False.
if condition:
    # code block to execute if the condition is true
else:
    # code block to execute if the condition is false

if-else statement Example

number = 12
if number >= 20:
    print("Number is greater than 20.")
else:
    print("Number is less than 20.")

From the example, given number is 12 and the condition number >= 20 evaluates to False, so it will execute else block of code and print “Number is less than 20”.

if-elif statement

if-elif Flowchart Python
if-elif Flowchart Python
  • elif (short for “else if“) statement is used to check multiple conditions.
  • If the condition in the if statement is False, then elif condition is evaluated.
  • If condition in the elif is True then code block under elif statement will be executed.
  • You can have multiple elif statements in a row.
if condition1:
    # code block to execute if the condition is true
elif condition2:
    # code block to execute elif condition 1 is true
elif condition3:
    # code block to execute elif condition 2 is true

if-elif statement Example

number = 10
if number > 15:
    print(number, "greater than 15")
elif number > 5:
    print(number, "greater than 5 but less than 15")
elif number == 10:
    print(number, "is exactly 10")

From the example, given number is 10 and the condition number > 15 evaluates to False, so it will check for the elif condition number > 5, which is True. Code block under first elif statement will be executed and print “10 greater than 5 but less than 15”.

if-elif-else statement

if-elif-else condition flowchart
if-elif-else condition flowchart
  • if-elif-else statement allows you to check multiple conditions.
  • The elif (short for “else if”) statement lets you test additional conditions if the previous if or elif condition was False.
  • The else block is executed only if all the previous conditions are False.
if condition1:
    # block of code to execute if condition1 is true
elif condition2:
    # block of code to execute if condition2 is true
else:
    # block of code to execute if all conditions are false

if-elif-else statement Example

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

In this program, given variable marks is 75.

  • We have defined if condition marks >= 90. For marks this condition is False.
  • Then it will check for elif condition marks >= 80, which again will be False.
  • Then next elif condition marks >= 70 will be checked. This will result in True and it will print “Grade: C”

Nested if-else statement

Nested if-else Flowchart Python
Nested if-else Flowchart Python
if condition1:
    # code block for if condition 1
    if condition 2:
         # code block for if condition 2
    else:
         # code block for else, if condition 2 is False
else:
    # code block for else, if condition 1 is False

Nested if-else statement Example

number = 10
number_2 = 20
if number > 5:
    if number_2 > 15:
        print(number, "greater than 5 and ", number_2, "is greater than 15")
    else:
        print(number, "greater than 5 but ", number_2, "is not greater than 15")
else:
    print(number, "is 5 or less")

From the example, given number is 10 and the condition number > 5 evaluates to True, so it will go inside the code block for that condition. For nested if statement, condition number_2 > 15 also evaluates to True. Code block under nested if statement will be executed and print “10 greater than 5 and 20 is greater than 15”.

Conditional statements with logical operators

Conditional statements (if, elif, else, nested if-else) can be used with logical operators (and, or, not) as well.

Example – if statement and and operator

number_1 = 15
number_2 = 25
if number_1 > 9 and number_2 > 18:
    print(number_1, "is greater than 9 and ", number_2, "is greater than 18")

In and operator example, both conditions are True, then if statement code block will be executed. number_1 > 9 is True but number_2 > 18 is True. Output “15 is greater than 9 and 25 is greater than 18”.

Example – if statement and or operator

number_1 = 15
number_2 = 12
if number_1 > 9 or number_2 > 18:
    print(number_1, "is greater than 9 and ", number_2, "is less than 18")

In or operator example, either one of if statement conditions are True, then if statement code block will be executed. number_1 > 9 is True but number_2 > 18 is False. Output “15 is greater than 9 and 12 is less than 18”.

match Statement

In Python, match statement were introduced in Python 3.10. It provides an easy and descriptive way to handle multiple conditions. match statement are similar to the “switch-case” statements in other programming languages. The match statement allows you to match a value against a series of patterns and execute code block for the first matching pattern. match Statement syntax:

match value:
    case pattern1:
        # code block for pattern1
    case pattern2:
        # code block for pattern2
    case _:
        # default code block (if no other patterns match)
  • match statement – Evaluates the value trying to match. This is generally a variable which needs to match for the given case patterns.
  • case statements – Define possible patterns that the value can match against. The variable given will match for the case pattern and the code block associated with first matching pattern will be executed.
  • Wildcard (_) case – This acts as a default case. If no case pattern matches then default case will be executed.
  • Case patterns can be defined to literals, strings, datatypes, collection pattern, Class and even wildcard patterns.

match Statement with Literal values

status = 400
match status:
    case 200:
        print("OK")
    case 400:
        print("Bad Request")
    case 404:
        print("Not Found")
    case _:
        print("Unknown Status")

In this program, we are using match statement, matching for variable status. Case patterns are literal numeric values. status value will match to case 400 and will print “Bad Request”. It can defined with literal values of string or other datatypes.

match Statement with Datatypes

value = tuple("shbytes")
match value:
    case int():
        print("value is of integer datatype.")
    case str():
        print("value is of string datatype.")
    case list():
        print("value is of list datatype.")
    case tuple():
        print("value is of tuple datatype.")
    case _:
        print("some other datatype.")

In this program, we are using match statement, matching for variable value. Cases are using datatype() patterns to match. Variable value datatype is Tuple. It will match for case tuple() and will print “value is of tuple datatype”. Similarly, it can match for other datatype objects.

match Statement with Patterns and Structure Evaluation

match statement capability is very significant when dealing with complex data structures like lists, tuples, and dictionaries. We can use use pattern matching to structure evaluation and work with these structures.

point = (12, 15)

match point:
    case (0, 0):
        print("Origin")
    case (x, 0):
        print(f"Point on X-axis at x={x}")
    case (0, y):
        print(f"Point on Y-axis at y={y}")
    case (x, y):
        print(f"Point at x={x}, y={y}")

In this program, we are using match statement, matching for variable point which is defined of Tuple datatype. Cases are using pattern matching or structural evaluation for tuple objects. These cases either match for absolute values like (0, 0) or takes elements as variable for structural evaluation like (x, y). Variable point (12, 15) which has both non-zero values will match with structure (x, y), where x = 12 and y = 15. It will print “Point at x=12, y=15”.

match Statement with Classes

from dataclasses import dataclass

@dataclass
class Coordinates:                  # Class definition
    latitude: float
    longitude: float

coord = Coordinates(15.65, 45.56)
match coord:
    case Coordinates(0, 0):
        print("Origin")
    case Coordinates(latitude, 0):
        print(f"Coordinates at latitude={latitude} and longitude 0")
    case Coordinates(0, longitude):
        print(f"Coordinates at latitude 0 and longitude={longitude}")
    case Coordinates(latitude, longitude):
        print(f"Coordinates at latitude={latitude}, and longitude={longitude}")
    case _:
        print("Unknown coordinates")

In this program, We have defined a Class Coordinates which takes two variables latitude and longitude. We have also defined a variable coord referencing to class Coordinates object. We are using match statement, matching for variable coord to the patterns from Coordinates class. These cases either match for absolute values like Coordinates(0, 0) or takes elements as variable for structural evaluation like Coordinates(latitude, longitude). Variable coord Coordinates(15.65, 45.56) which has both non-zero values will match with structure Coordinates(latitude, longitude), where latitude = 15.65 and longitude = 45.56. It will print “Coordinates at latitude=15.65, and longitude=45.56”.

Summary

In this article, we learned about flow controls statements like conditional statements and match statements. Various scenarios for if, elif, else and match statements were covered.

    Python Topics


    Comments

    No comments yet. Why don’t you start the discussion?

    Leave a Reply

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