Category: Python Control Statements

  • Control Statements in Python

    In Python, control statements are used to alter the flow of execution in a program. They help make decisions, repeat actions, or skip parts of code based on certain conditions.

    In Python, there are mainly three types of Control Statements:

    1. Conditional Statements
    2. Loop Statements
    3. Jump Statements

    Conditional Statements

    As the name suggests, conditional statements (also known as decision-making statements) are used to make decisions in code. These statements evaluate the Boolean expression and control the flow of the program on the basis of the result of the condition specified.

    There are primarily three types of decision-making statements in Python – ifif…else, and if…elif…else.

    1) if Statement

    The if statement helps us check if a given condition is true. In case, the specified condition evaluates to True, the associated block of code is executed.

    Let us see an example of Python if statement.

    Example

    # simple example of python if  
      
    x = 10  
      
    # if statement  
    if x > 5:  
      # inside if block  
      print("x is greater than 5")  

    Output:

    x is greater than 5

    Explanation:

    In the above example, we are given a variable x initialized with the value 10. We have used the if conditional statement to check if the value of x is greater than 5 (x > 5). Inside the if block, we have printed some statement.

    Since the condition x > 5 is True, i.e., 10 > 5, therefore, the code inside the if-block is the executed and the specified statement is printed.

    2) if…else Statement

    The if-else statement is an extension of the basic if statement. In if-else, there is an alternative code block that is executed if the given condition is false. This way we can ensure that one of the two possible action is always carried out on the basis of the result of the condition.

    Let us take a look at the following example of Python if…else statement.

    Example

    # simple example of python if-else  
      
    x = 3  
      
    # if-else statement  
    if x > 5:  
      # inside if block  
      print("x is greater than 5")  
    else:  
      # inside else block  
      print("x is less than or equal to 5")  

    Output:

    x is less than or equal to 5

    Explanation:

    In the above example, we are given a variable x initialized with the value 3. We have used the if-else conditional statement to check if the value of x is greater than 5 (x > 5). Inside the if block, we have printed some statement. Similarly, in the else block, we have added another statement for execution.

    Since the condition x > 5 is False, i.e., 3 is not greater than 5, therefore, the code inside the else-block is the executed and the specified statement is printed.

    3) if…elif…else Statement

    The if-elif-else statement allows us to check multiple conditions sequentially. The conditions are evaluated one by one; if once a condition is true, the block corresponding to it is executed, and the remaining conditions are ignored. The else block executes only when none of the conditions are true.

    We will now see an example of Python if…elif…else statement.

    Example

    # simple example of python if-elif-else  
      
    x = 5  
      
    # if-elif-else statement  
    if x < 5:  
      # inside if block  
      print("x is less than 5")  
    elif x > 5:  
      # inside elif block  
      print("x is greater than 5")  
    else:  
      # inside else block  
      print("x is equal to 5")  

    Output:

    x is equal to 5

    Explanation:

    In the above example, we are given a variable x initialized with the value 5. We have used the if-elif-else conditional statement to check if the value of x is less than, greater than or equal to 5. Inside the if block, we have printed some statement. Similarly, in the elif and else block, we have added some more statements for execution.

    Since the condition x < 5 and x > 5 is False therefore, the code inside the if and elif blocks are ignored and the statement from the else block is printed.

    Loop Statements

    Loop statements are the statements used for repeating a set of instructions multiple times for given condition. These statements allow us to automate repetitive tasks like counting, processing data, or checking conditions.

    With the help of loops, we are not required to write the same code over and over again, making our program much cleaner, and easier to maintain.

    In Python, we have two types of loops – for and while.

    1) for Loop

    Python for loop is used to iterate over a given sequence (like list, tuple, string or range). It allows us to repeat a block of code for each element in the sequence.

    Here is an example of Python for.

    Example

    # simple example of python for  
      
    beverages = ['tea', 'coffee', 'water', 'juice', 'milk']  
      
    # iterating over the list using for loop  
    for beverage in beverages:  
        print(beverage)  

    Output:

    tea
    coffee
    water
    juice
    milk
    

    Explanation:

    In this example, we are given a list consisting of some items. We then used the for loop to iterate through the elements of given list and printed them. As a result, each element is printed in order.

    2) while Loop

    Python while loop is used to repeatedly execute a block of code as long as a given condition remains True. It is useful when the number of iterations is unknown beforehand.

    We will now see an example of Python while.

    Example

    # simple example of python while  
      
    # initializing counter  
    count = 1  
    # looping with while loop  
    while count <= 5:  
      # inside while loop  
      print(count, "Learn Python")  
      # incrementing by 1  
      count += 1  

    Output:

    1 Learn Python
    2 Learn Python
    3 Learn Python
    4 Learn Python
    5 Learn Python

    Explanation:

    Here, we have initialized a variable with the value 5 and created a while loop that executes a block of code as long as the initialized variable is less than and equals to 5. This code block includes a print statement and increments the variable value by 1.

    As a result, we entered the while loop as the condition is true. For each iteration, a statement is printed and the value of the variable is incremented by 1. Once counter reaches 6, the condition counter <= 5 becomes False, causing the loop to terminate.

    Jump Statements

    Jump statements, also known as loop control statements, are used to transfer the control of the program to the specific statements. In other words, jump statements transfer the execution control to the other part of the program. There are three types of jump statements in Python – breakcontinue and pass.

    1) break Statement

    The break statement helps us stop a loop immediately, even if the condition has not been fully met. When we use break, the control exits the loop and moves to the code after it. We usually use it when we have found what we are looking for or when continuing the loop is no longer needed.

    Let us see an example of Python break.

    Example

    # simple example of python break  
      
    # using for loop  
    for number in range(1, 10):  
      # checking if the current number is 6  
      if number == 6:  
        print("Found it!")  
        # using break to terminate the loop  
        break  
      print(f"Checking {number}")  

    Output:

    Checking 1
    Checking 2
    Checking 3
    Checking 4
    Checking 5
    Found it!
    

    Explanation:

    In the above example, we have used the for loop to iterate over a numbers in a given range. Inside this loop, we have added a condition checking if the number in the current iteration is equal to 6 and used the break keyword to terminate the next iterations.

    As a result, the numbers are iterated for the given range. When the number becomes 6, the loop terminates due to the break statement.

    2) continue Statement

    Python continue statement allow us to skip the current iteration of a loop and jump straight to the next one. We generally use it when we want to ignore specific cases in a loop without stopping the entire loop. It lets us control the flow more precisely by skipping only the unwanted part.

    Example

    # simple example of python continue  
      
    names = ['John', '', 'Michael', 'Sachin', '', '', 'Irfan']  
      
    # using for loop  
    for name in names:  
      # if there is an empty string in the list  
      if name == "":  
        # using the continue statement to skip the current iteration  
        continue  
      print(f"Hello, {name}!")  

    Output:

    Hello, John!
    Hello, Michael!
    Hello, Sachin!
    Hello, Irfan!
    

    Explanation:

    Here, we are given a list consisting of some names and empty strings. We have used the for loop to iterate over this list. We have also used the continue keyword to skip the current iteration if the current list element is an empty string.

    As a result, the elements with empty strings are skipped and the names from the list are printed.

    3) pass Statement

    We can write placeholder code using the pass statement. It does nothing when executed; however it is useful to create a syntactically correct block that we plan to fill in later. Python pass is generally used while defining a loop, function, or condition where we have not written any logic yet.

    Let us see a simple example of Python pass.

    Example

    # simple example of python pass  
      
    # using for loop  
    for i in range(1, 6):  
      if i == 3:  
        # using pass keyword  
        pass  
      else:  
        print(i)  

    Output:

    1
    2
    4
    5
    

    Explanation:

    In the above example, we have used the for loop to iterate over a specific range. Inside this loop, we have used the pass statement as the placeholder inside if-else block.

    Conclusion

    In this tutorial, we have learned about control statements in Python with the help of examples. We discussed that there are mainly three types of control statements used in Python that includes decision-making, loop, and jump statements.

    Decision-making statements helps us make decisions in code. These statements includes if, if-else, and if-elif-else statements. Whereas the loop statements helps us repeat a block of code for multiple times using the for and while loop. The jump statements like break, continue and pass helps us transfer the control of the program to the particular statements.

  • Difference Between For Loop and While Loop in Python

    In Python, the for loop and while loop are two of the basic operations used to repeat a specified action multiple times. Both loops do share similarities; however, they have distinct mechanics and applications. We generally use the for loop in case the number of iterations is known in advance, and we use the while loop for an unknown number of iterations.

    What is a For Loop in Python?

    The Python for loop is a programming mechanism used for iterating over a sequence until a given condition is met.

    The for loop in Python allows us to iterate over iterable objects, such as tuples, lists, dictionaries, and strings, until it reaches the termination of the sequence or the condition is fulfilled. The for loop proceeds to the next step after each iteration is completed.

    For Loop Syntax in Python

    It has the following syntax:

    for var_name in sequence:  

    Parameter(s):

    • var_name: A name of a variable assigned to each element in the given sequence
    • sequence = Sequence refers to iterable elements such as lists, tuples, dictionaries, and strings
    • The loop executes once for each item in the iterable.
    • The indented block under the loop runs on every iteration.

    Examples of Python For Loop

    We will now look at some examples of Python ‘for’ loop:

    Basic Example of a For Loop in Python

    In this example, we will see a basic example of Python For Loop:

    Let us see through a simple example to understand how the For Loop works:

    Example

    #let's  print numbers in a for loop using Range()  
    for i in range(1,7): #Here we have used for loop  
        print (i)   

    Output:

    1
    2
    3
    4
    5
    6
    

    Explanation:

    In the above example, we used a for loop with the range() function to print numbers ranging from 1 to 6.

    Another Example: Use of range() with For Loop

    We will now take a look at an example to understand the working of the ‘for’ loop with the range() function.

    Example

    #receiving the input from the users  
    row = int(input("Enter number of rows: "))  
    #using the range function in a For Loop  
    for i in range(1, row + 1):  
        # Print spaces  
        for j in range(row - i): #nested loop used  
            print("  ", end="")  
          
        # Print stars  
        for stars in range(2 * i - 1):    
            print("* ", end="")  
          
        print()    

    Output:

    Enter number of rows: 5
    *
    * * *
    * * * * *
    * * * * * * *
    * * * * * * * * *
    

    Explanation:

    The above code is an example of a Nested loop, where we have printed star patterns using a Nested For Loop.

    What is the While Loop?

    Python is used to repeatedly execute a block of code as long as a given condition remains True. It is useful when the number of iterations is unknown beforehand.

    Syntax:

    while condition:    
    
        # code block   
      • condition: A Boolean expression that is evaluated before each iteration.
      • The code block inside the loop is executed only if the condition is true.
      • If the condition never becomes False, the loop will run infinitely, potentially causing an infinite loop.

      Examples of Python While Loop

      We will now look at some examples of Python while loops:

      Basic Example of While Loop

      In this example, we will see how the While loop functions in Python.

      Example

      # initializing a counter variable    
      counter = 0    
      # using the while loop to iterate the counter up to 5    
      while counter < 5:    
        # printing the counter value and some statement    
        print(counter, "Hello")    
        # incrementing the counter value    
        counter += 1    

      Output:

      0 Hello
      1 Hello
      2 Hello
      3 Hello
      4 Hello
      

      Explanation:

      In the above example, we have initialized a variable counter with the value 0. Then, we enter a while loop that executes the block of code as long as the counter is less than 5. Within the loop, we have printed the current value of the counter, followed by “Hello”. After each iteration, the counter is incremented by 1. Once the counter reaches 5, the condition counter < 5 becomes False, causing the loop to terminate.

      Another Example: Use of the While loop with ‘else’

      In this example, we will see how to use the While loop with the ‘else’ statement

      Example

      # initializing counter    
      i = 1    
          
      # iterate using the While loop    
      while i <= 3:    
          print(i)    
          i += 1    
          # else block    
      else:    
          print("Loop completed successfully!")    

      Output:

      1
      2
      3
      Loop completed successfully!
      

      Explanation:

      In this example, we have created a counter with an initial value of 1. We have then used the While loop with the ‘else’ statement to iterate under a specified condition. Inside this loop, we printed the counter value and increment it by 1. This loop iterates until the condition remains True. Under the ‘else’ block, we have printed a statement that runs when the condition becomes False.

      Key differences between For Loop and While Loop

      There are several differences between the for loop and the while loop in Python. Some main differences are as follows:

      Featurefor Loopwhile Loop
      DefinitionIterates over a sequence (like a list, string, or range).Repeats a block of code as long as a condition is True.
      UsageWhen the number of iterations is known or a sequence is available.When the number of iterations is unknown or depends on a condition.
      Syntaxfor variable in iterable:
      # code block
      while condition:
      # code block
      Loop ControlControlled by an iterable (e.g., list, tuple, range).Controlled by a condition that must eventually become false.
      Loop VariableAutomatically updates with each iteration.Needs to be manually updated inside the loop.
      Risk of Infinite LoopLow, since it depends on an iterable.Higher, if the condition is never made false.
      Common Use CasesIterating over items in a list, string, dictionary, etc.Waiting for user input, checking sensor data, or running until a condition.
      Structure SimplicityMore concise when working with sequences.More flexible for complex or dynamic conditions.
      TerminationEnds automatically when the iterable is exhausted.Ends only when the condition becomes false.
    1. Difference Between break and continue in Python

      In Python, the break and continue statements determine the flow of program execution. These statement control when the program continues the process and when it breaks execution.

      Difference Between break and continue in Python

      The break Statement

      The break Statement is used to abruptly stop the flow of the program, hence forcing the program to break out of the continuous or infinite loop.

      Syntax:

       #block of code  
      
      break

        Example: break Statement

        Let’s see an example where we will use the break statement.

        Example

        # Here we will iterate from number 1 to 10  
        for num in range(1, 11):    
            if num % 2 == 0:    
                break  # using the break statement to abruptly stop the functioning of the program   
            print(num)    

        Output:

        1
        

        Explanation

        In the above example, we used the break statement, which immediately stopped the flow of the program after the first iteration, and the output printed was only 1. It means as soon as the 1 is iterated, the break statement does its job.

        The continue Statement

        The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration and proceed to the next iteration immediately.

        We use the continue statement in some conditions where we want some situations to be completely ignored without affecting anything or breaking out of the entire loop. The Python continue statement in Python can be used in for and while loops to improve code efficiency and readability.

        Syntax:

        # jump statement    
        
        continue;

        Example: continue Statement

        Let’s take the same example to see what will happen if we use the continue statement.

        Example

        # Here we will iterate from number 1 to 10  
        for num in range(1, 11):    
            if num % 2 == 0:    
                continue  # it skips the rest of the loop for even numbers    
            print(num)    

        Output:

        1
        3
        5
        7
        9
        

        Explanation

        In the above example, the continue statement is executed for every number known as num, which causes the program to skip the print(num) function and move on to the next iteration.

        break  Vs. continue Statement

        Let’s quickly recap the difference between break and continue, which will help us remember the key points.

        break Statementcontinue Statement
        The Break Statement in Python is used to abruptly stop the flow of the program.The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration.
        It is commonly used inside switch blocks and is also valid in for, while, and do-while loops.It is not applicable in switch statements but can be used in for, while, and do-while loops.
        Once the break is executed, control moves directly outside the loop or switch structure.When continue is executed, control jumps to the next cycle of the loop.
        Syntax: break;Syntax: continue;
        It can be combined with labeled statements to exit outer loops in nested structures.It does not support labeled usage for controlling outer loop flow.
        Any remaining loop iterations are completely skipped after the break is triggered.Remaining iterations still run, except the iteration in which continue appears.

        Conclusion

        Break and Continue statement acts like a steering wheel that controls the flow of the program by deciding whether to continue the process or break it abruptly.

        They both use the syntax of their name, such as break and continue, respectively, followed by the colon(;). We used examples and output with their explanation to understand the working of these statements in the program. Lastly, we recapped the tutorial by making the tabular differences of Break and Continue.

      1. Python Pass Statement

        In Python, the pass Statement acts as a null operator or placeholder. It is applied when a statement is required syntactically, which means that the statement will be visible in the code but will be ignored; hence, it returns nothing.

        Syntax of the Pass Statement

        The following below is the syntax of the pass statement in Python:

        Syntax:

         def func_name():  
        
            pass

          Simple Python Pass Statement Example

          Let us see a simple example to understand how Python’s pass statement works:

          Example

          # a function to send greetings  
          def greeting():  
              # using pass statement  
              pass # this acts as a placeholder  
            
          # calling the function  
          greeting()  

          Explanation:

          Here, we have defined a function greeting() and used the pass statement to represent the placeholder.

          Since this function is empty and returns nothing due to the pass statement, there will be no output when we call this function.

          Using Pass Statement in Conditional Statements

          The Pass statement in Conditional statements – if, else, elif, is used when we want to leave a space or placeholder for any particular condition.

          Example

          n=5  
          if n>5:  
              pass # this works as a placeholder  
            
          else:  
              print("The defined number n is 5 or less than 5")  

          Output:

          The defined number n is 5 or less than 5
          

          Explanation:

          In this example, we used the pass statement in the if-block of the if-else statement. Here, the pass statement is a placeholder indicating that a piece of code can be added in the if-block in the future.

          Using Pass Statement in Loops

          Pass statements in Loops – for, while, are used to symbolize that no action is performed and required during iteration.

          Example

          for i in range(10):  
              if i == 5:  
                  pass #It will give nothing when i=5  
              else:  
                  print(i)   

          Output:

          0
          1
          2
          3
          4
          6
          7
          8
          9
          

          Explanation:

          When the Pass Statement is used in the ‘if’ condition, it will print every number in the range of 0 to 10 except 5.

          Using Pass Statement in Classes:

          A pass statement in a Class is used to define an empty class and also as a placeholder for methods that can be used later.

          Example

          class Learn Python:  
              pass   
          class Employees:  
              def __init__(self,first_name,last_name):  
                  self.ft_name=ft_name #ft_name means first name  
                  self.lt_name=lt_name #lt_name means last name  
              def ft_name(ft_name):  
                  pass #placeholder for first name  
              def l_name(l_name):  
                  pass #placeholder for last name  

          Explanation:

          The Learn Python class has no methods or attributes; here, the pass statement is used to describe an empty class.
          In the Employees class, the first and last name methods are defined, but they produce nothing, as indicated by the pass keyword.

          Conclusion

          A pass statement is a prominent way to be used as a placeholder, which does not give any output. It can be used in conditional statements, loops, functions, and classes, which provides coders with a way to define the structure of the code without executing any functionality temporarily.

        1. Python Break Statement

          In Python, the break is a keyword used to prematurely exit a loop, before the loop iterates through all the elements or met its condition. When we execute the break statement, the program immediately terminates the loop, shifting the control to the next line of code after the loop. The break is commonly used in the cases where we need to exit the loop for a given condition.

          Syntax of the Python Break Statement:

          The syntax of the break statement in Python is given below:

           # jump statement  
          
          break;

            When executed, break causes the loop to terminate and proceeds to the next line of code. In the case of nested loops, break affects only the innermost loop.

            Simple Python Break Statement Example

            Here is a simple example to demonstrate how the break statement works in Python.

            Example

            # Loop through numbers from 1 to 10    
            for num in range(1, 11):    
                if num == 6:  
                    break  # breaking the loop at 6  
                print(num)  

            Output:

            1
            2
            3
            4
            5
            

            In this example, we loop through the numbers from 1 to 10. We have used the if-statement to execute the break statement when num = 6.

            As a result, the number from 1 to 5 is printed and the loop terminates when it reaches 6.

            Flowchart of the break Statement in Python

            The following is the flowchart of the Python break statement:

            Python Break Statement

            Step 1: Start the loop

            Step 2: Check the loop condition

            Step 3: If the loop condition is False, exit the loop.

            Step 4: If the loop condition is True, proceed to the loop body.

            Step 5: Inside the loop, evaluate a condition to decide whether to break.

            Step 6: If the break condition is True, execute the break statement – immediately exit the loop.

            Step 7: If the break condition is False, continue executing the loop body.

            Step 8: After completing the current iteration – Go to the next iteration.

            Step 9: Repeat steps 2-8 until the loop ends naturally or via break

            Different Examples of the break Statement

            Let us now see some more examples showing the use of the break statement in Python.

            Example 1: Break Statement with for Loop

            In Python, a ‘for’ loop is used to iterates over a given sequence (e.g., list, tuple, string or range), and executes a block of code for each item in the sequence. We can use the break statement within the ‘for’ loop in order to terminate the loop before it iterates over all elements, on the basis of a specified condition.

            We will take a look an example show how to find an element from a list using the for-loop and the break statement.

            Example

            # given list  
            fruit_basket = ['apple', 'mango', 'banana', 'orange', 'kiwi', 'watermelon', 'blueberries']  
              
            # using the for loop to iterate through the list  
            for index, fruit in enumerate(fruit_basket):  
                # if the fruit is equal to kiwi, then break the loop  
                if fruit == 'kiwi':  
                    print("Fruit found!")  
                    break   # break statement  
              
            # printing the index of the located element  
            print("Located at index =", index) 

            Output:

            Fruit found!
            Located at index = 4
            

            Explanation:

            In the above example, we are given a list consisting of some fruits. We used the ‘for’ loop to iterate through the list. We used the enumerate() function to add a counter to the list. Inside the loop, we used the ‘if’ statement to check if the current element is ‘kiwi’. We then break the loop using the ‘break’ statement. At last, we printed the index value of the located element.

            Example 2: Break Statement with While Loop

            In Python, a ‘while’ loop repeatedly executes a code block as long as a particular condition is True. We can use the break statement within a while loop in order to exit the loop on the basis of dynamic conditions that may not be known in advance.

            Let us see an example to understand how to use the break statement with the while loop.

            Example

            # initializing the counter  
            count = 1  
              
            # usign the while loop  
            while True:  
              
                print("Count:", count)  
                # if the counter's value is 5, then break the loop  
                if count == 5:  
                    print("Condition met! Exiting loop.")  
                    break # using the break statement  
                # incrementing the counter by 1  
                count += 1  

            Output:

            Count: 1
            Count: 2
            Count: 3
            Count: 4
            Count: 5
            Condition met! Exiting loop.
            

            Explanation:

            In this example, we initialize a variable, ‘count’ with 1 and used the ‘while’ loop that will run infinitely until the condition is True. Inside the ‘while’ loop, we printed the current value of the ‘count’ variable. We used the ‘if’ conditional statement to check if count’s value is 5 and used the ‘break’ statement to break the loop. At last, we incremented the value of the variable by 1.

            Example 3: Break Statement with Nested Loop

            In Python, nested loops are the loops within loops. It allow us to perform more complex iterations, like looping over multi-dimensional data structures. While using the break statement within nested loops, it is important to understand its scope.

            • Innermost Loop Exit: A break statement will only exit the loop in which it is directly placed.
            • Exiting Multiple Loops: In order to exit multiple levels of nested loops, we need to use additional strategies like adding flags, or encapsulating loops within functions.

            Here is an example of using the break statement in nested loops to search for a number in a 2D list:

            Example

            # given 2D list  
            matrix = [  
                [10, 15, 20],  
                [25, 30, 35],  
                [40, 45, 50]  
            ]  
            # element to be searched  
            target = 30  
              
            found = False  # Flag to track if the number is found  
              
            # using the for nested loop  
            for row in matrix:  
                for num in row:  
                    # if the current element is equal to the target value, set flag to True and break the loop        
                    if num == target:  
                        print(f"Number {target} found! Exiting loops.")  
                        found = True  
                        break  # using break statement  
                # exiting the outer loop  
                if found:  
                    break  

            Output:

            Number 30 found! Exiting loops.
            

            Explanation:

            In this example, we are given a 2D list and a value to be searched in the list. We initialized a flag as False and used the nested ‘for’ loop to traverse the elements of the 2D list. We then used the ‘if’ statement to check for the target value in the list and used the ‘break’ statement to break the inner loop, once found. Then we again used the ‘break’ statement to exit the outer loop.

            Conclusion

            Python provides the break statement which helps programmers execute loop termination based on specific conditions. The break statement functions best at preventing waste in for loops and while loops and nested loops to enhance their speed. Multiple conditions exist for using break in nested loops because the exit command affects only the innermost loop thus requiring supplementary logic to terminate outer loops. The controlled use of break improves program efficiency by making the expression best suited for search operations and data processing and real-time monitoring needs.

          1. Python Continue Statement

            The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration and proceed to the next iteration immediately. It is useful when some specified conditions need to be ignored without terminating or breaking out of the entire loop. The continue statement in Python is used in for and while loops to improve code efficiency and readability.

            Python Continue Statement

            Syntax of the Continue Statement:

            The syntax of the Python Continue statement is as follows:

            # jump statement  
            
            continue;

            When the continue statement is executed in Python, it enables the loop to skip the rest of the code in the current iteration and immediately advances to the next iteration. In the case of nested loops, the continue statement only affects the innermost loop.

            Simple Python Continue Statement Example

            Let’s see a simple example to understand how the continue statement works:

            Example

            # Loop through numbers from 1 to 10  
            for num in range(1, 11):  
                if num % 2 == 0:  
                    continue  # Skip the rest of the loop for even numbers  
                print(num)  

            Output:

            1
            3
            5
            7
            9

            Explanation:

            In the above example, the continue statement is executed for every number known as num, which causes the program to skip the print(num) function and move on to the next iteration.

            Flowchart of the continue Statement in Python

            The following is the flowchart of the Python continue statement:

            Python Continue Statement

            Explanation of the Flowchart of Python Continue Statement:

            Step 1: Initially, the loop starts.

            Step 2: The condition of the loop is checked.

            Step 3: If the ‘continue’ condition is achieved:

            • It skips the remaining elements in the loop.
            • Then, it jumps to the next iteration.

            Step 4: Otherwise, the remaining loop body is executed.

            Step 5: The entire process gets repeated until the loop terminates.

            Different Examples of the continue Statement

            Let us now see some more examples showing the use of the continue statement in Python.

            Example 1: Skipping Specific Values

            Let us take an example to demonstrate how to skip specific value in Python using continue statement.

            Example

            # here we are iterating through the characters in the string  
            for char in "Python Programming":    
              # skipping the character 'o'    
              if char == 'o':    
                continue    
              # printing the characters    
              print(char, end='')    

            Output:

            Pythn Prgramming

            Explanation:

            Here, the letter ‘o’ is skipped whenever it appears in the string.

            Example 2: Skipping Iterations in a while Loop

            Let us take an example to demonstrate how to skip iterations in while loop using the continue statement.

            Example

            # initializing value of x as 0  
            x = 0  
            # using the while loop  
            while x < 10:  
              # incrementing the value of x upto 10  
              x += 1  
              if x == 5:  
                continue  # Skip printing when x is 5  
              # printing the value of x  
              print(x)  

            Output:

            1
            2
            3
            4
            6
            7
            8
            9
            10

            Explanation:

            When x equals 5, the continue statement prevents print(x) from executing, and the loop proceeds with the next iteration.

            Example 3: Skipping Negative Numbers in a List

            Let us take an example to demonstrate how to skip negative numbers in a list using the continue statement.

            Example

            # list of numbers  
            numbers = [10, -3, 5, -8, 7]  
              
            # iterating through the elements of the list  
            for num in numbers:  
              # skipping a number less than 0  
              if num < 0:  
                continue  
              # printing the numbers  
              print(num)  

            Output:

            10
            5
            7

            Explanation:

            In this example, negative numbers are skipped, and only positive numbers are printed.

            Example 4: Skipping Certain Words in a Sentence

            Let us take an example to demonstrate how to skip certain words in a sentence using the continue statement.

            Example

            # given sentence  
            sentence = "Python learn from a Learn Python App"  
            # list of words to skip  
            words_to_skip = ["from", "a"]  
              
            # using for-loop  
            for word in sentence.split():  
                if word in words_to_skip:  
                    continue    # continue statement to skip the words from given list  
                print(word, end=' ')  

            Output:

            Python learn Python App

            Explanation:

            Here, the words “from” and “a” are skipped while printing the rest of the sentence.

            Example 5: Skipping Multiples of 3 in a Range

            Let us take an example to demonstrate how to skip multiples of 3 in a range using the continue statement.

            Example

            # for loop to iterate through 1 to 20  
            for num in range(1, 20):  
              # skipping the multiples of 3   
              if num % 3 == 0:  
                continue  
              # printing the numbers  
              print(num, end=' ')  

            Output:

            1 2 4 5 7 8 10 11 13 14 16 17 19

            Explanation:

            This example skips numbers that are multiples of 3 while printing the rest.

            Example 6: Skipping Empty Strings in a List

            Let us take an example to demonstrate how to skip empty strings in a list using the continue statement.

            Example

            # here is the list of words    
            words = ["apple", "", "banana", "cherry", ""]    
                
            # using a for-loop to iterate through the words in the list    
            for word in words:    
              # skipping the empty string from the list    
              if word == "":    
                continue    
              # printing the words from the list    
              print(word)    

            Output:

            apple
            banana
            cherry

            Advantages of Python Continue Statement

            There are several advantages of using the Continue Statement in Python. Let’s see some of them:

            Python Continue Statement
            • Skipping Unwanted Iterations: If there’s a need to omit some value(s) in the loop, repeating sequences while the remainder of the iterations are still executed, the loop can be used.
            • Avoiding Nested if Conditions: Unwanted nested if statements are easily removed, and code is made less complex with a single continue statement. Controlling the flow of a program with continue is airy.
            • Efficient Filtering: In most cases where data is being processed through lists or iterations, unwanted values can be bypassed via continue.
            • Performance: The term continues, in regard to loops of computation or operation, moves the remaining parts of the loop of calculation to the next iteration; thus, in cases where particular operations are not needed, continuing assists in bringing forth suitable efficiency when it comes to value or return.
            • Specific Conditions: If there’s a request to omit an operation on certain conditions without getting out of the loop, continuing is the best option available.

            Conclusion

            The use of a specific loop iteration can be skipped by utilizing the “continue” statement in Python without exiting the iteration process. This comes in handy when certain conditions should be left out while processing other elements that form a sequence. The code structure becomes simple and makes comprehending the loops easier, which ultimately increases the efficiency of the program.

          2. Python While Loop

            Python While Loop is used to repeatedly execute a block of code as long as a given condition remains True. It is useful when the number of iterations is unknown beforehand. The While loop can be utilized by using the while keyword and a colon(:).

            In the Python while loop, there can be a single statement or multiple statements with proper indentation. The While enables the program to run till the given condition is True; it stops as soon as the condition fails. If the condition doesn’t fail, the program goes into an infinite loop and doesn’t stop unless forced.

            Syntax of the while Loop

            Let’s see the basic syntax of the While loop in Python:

              while condition:    
            
              # The Code to be executed as long as the condition remains true

              Syntax Explanation:

              The Python While loop evaluates the specified conditional expression. The while loop executes the program if the given condition turns out to be True. When the entire code block is executed, the condition is checked again, and this process is repeated until the conditional expression returns False.

              Simple Python while Loop Example:

              Let us take a look at a simple example of a Python while loop.

              # initializing a counter variable    
              
              counter = 0    
              
              # using the while loop to iterate the counter up to 5    
              
              while counter < 5:    
              
                # printing the counter value and some statement    
              
                print(counter, "Hello")    
              
                # incrementing the counter value    
              
                counter += 1

              Output:

              0 Hello
              1 Hello
              2 Hello
              3 Hello
              4 Hello
              

              Explanation:

              In the above example, we have initialized a variable counter with the value 0. We then enter a while loop that executes the block of code as long as the counter is less than 5. Within the loop, we have printed the current value of the counter, followed by “Hello”. After each iteration, the counter is incremented by 1. Once the counter reaches 5, the condition counter < 5 becomes False, causing the loop to terminate.

              Flowchart of the While Loop in Python

              The following flowchart represents the working of a ‘while’ loop:

              Python While Loops

              Step 1: The program starts.

              Step 2: The while loop checks whether the specified conditional expression is True or False.

              • If True, it proceeds to the loop body.
              • If False, it exits the loop and moves to the next part of the program.

              Step 3: If the condition is True, execute the statements inside the loop.

              Step 4: Modify the variable controlling the loop (e.g., incrementing a counter).

              Step 5: Go back to Step 2 and re-evaluate the condition.

              Step 6: Once the condition becomes False, it exits the loop and continues with the rest of the program.

              Note: Indentation is required to define the code block inside a while loop. Improper or Incorrect indentation can cause syntax errors or logical errors (like infinite loops). Any non-zero number in Python is interpreted as Boolean True. False is interpreted as None and 0.

              Examples of Python while Loop

              We will now take a look at some basic examples of the while loop in Python.

              Finding Numbers Divisible by 5 or 7 Using a while Loop

              Here, an example is given that elaborates on how to find numbers between 1 and 50 that are divisible by 5 or 7 using the while loop in Python.

              Example:

              # initializing a iterable as 1  
              i = 1  
                
              # using the while loop to find numbers between 1 to 50 that are divisible by 5 or 7  
              while i < 50:  
                if i % 5 == 0 or i % 7 == 0:  
                  print(i, end=' ')  
                i += 1   

              Output:

              5 7 10 14 15 20 21 25 28 30 35 40 42 45 49

              Explanation:

              In the above example, we are finding the numbers that are divisible by 5 and 7 till the numbers in the loop are less than 50. We start from the initial number 1 and increment it. As soon as the number 50 is reached, the loop gets terminated.

              Finding the Sum of Squares Using a While Loop

              In the following example, we will show how to calculate the sum of squares of the first 15 natural numbers using the while loop in Python.

              Example

              # initializing variables  
              sum = 0   # storing the sum of squares  
              counter = 1     # iterable  
                
              # using the while loop  
              while counter <= 15:  
                sum = counter**2 + sum  # calculating the sum of the squares    
                counter += 1    # incrementing the counter value  
              # printing the result  
              print("The sum of squares is", sum)  

              Output:

              The sum of squares is 1240

              Explanation:

              The above code calculates the sum of squares using a while loop from the numbers 1 to 15. We initialized the variable values of Sum equal to 0 and counter equal to 1. The while loop continues to run as long as the counter value remains less than or equal to 15. The program terminates when the while loop moves ahead to 16 as the condition fails there.

              Checking Prime Number using While Loop

              In the following example, we will show how to check whether a given number is Prime using while loop in Python.

              Example

              # creating a list of numbers  
              num = [34, 12, 54, 23, 75, 34, 11]  
                
              # defining a function to check prime number  
              def prime-number(number):  
                  c = 0    
                  i = 2    
                  while i <= number / 2:    
                      if number % i == 0:    
                          c = 1    
                          break    
                      i = i + 1  
                  if c == 0:  
                      print(f"{number} is a PRIME number")  
                  else:  
                      print(f"{number} is not a PRIME number")  
                
              for i in num:    
                  prime-number(i)    

              Output:

              34 is not a PRIME number
              12 is not a PRIME number
              54 is not a PRIME number
              23 is a PRIME number
              75 is not a PRIME number
              34 is not a PRIME number
              11 is a PRIME number
              

              Explanation:

              In the above example, we are checking whether the numbers in the list are Prime numbers or not. We initialized the value of c, which is equal to 0, and I equals 2. Using the conditions under the while loop and break statement to find out the prime numbers.

              Checking Armstrong Number Using while Loop

              In the following example, we will show how to check if the given integer is an Armstrong number using the while loop in Python.

              An Armstrong number is the sum of each digit raised to the power of the total number of digits. For example: 153 = 1^3 + 5^3 + 3^à 1+125+27 = 153

              Example

              n = int(input())    
              n1=str(n)    
              l=len(n1)    
              temp=n    
              s=0    
              while n!=0:    
                  r=n%10    
                  s=s+(r**1)    
                  n=n//10    
              if s==temp:    
                  print("It is an Armstrong number")    
              Else:    
                  print("It is not an Armstrong number ")    

              Output:

              It is an Armstrong number

              Explanation:

              The above code checks whether a given number is an Armstrong number or not. Initially, we take the input from the user and store it in the variable n. Then the number is converted into a string to calculate its length. We use temp to store the value of the number entered by the users. We initialized the variable s to 0, which will store the sum of powers of digits.

              The last digit of the number is found using the modulus operator and stored in r using the while loop. After the loop ends, the program compares the calculated sum s with the original number temp. If both are equal, it prints “It is an Armstrong number”; otherwise, it prints “It is not an Armstrong number”.

              Creating Table of Multiplication Using the While Loop

              In this example, we will show how to create a multiplication table for a given number using the while loop in Python.

              Example

              num = 21    
              counter = 1    
              # We will use a while loop to iterate 10 times for the multiplication table            
              print("The Multiplication Table of: ", num)      
              while counter <= 10: # specifying the condition    
                  ans = num * counter    
                  print (num, 'x', counter, '=', ans)          
                  counter += 1 # expression to increment the counter  

              Output:

              The Multiplication Table of: 21
              21 x 1 = 21
              21 x 2 = 42
              21 x 3 = 63
              21 x 4 = 84
              21 x 5 = 105
              21 x 6 = 126
              21 x 7 = 147
              21 x 8 = 168
              21 x 9 = 189
              21 x 10 = 210
              

              Explanation:

              In the above example, we are creating a multiplication table of a pre-defined number, 21. We initialized the counter value to 1 and incremented it as the while loop runs. The while loop will function till the counter is less than or equal to 10. These incremented numbers till 10 are multiplied by 21, giving us the multiplication table.

              Infinite while Loop in Python

              An infinite while loop in Python is caused when the condition always remains true. This causes the loop to run endlessly until the memory gets full.

              Let’s see an example where the while loop runs infinitely:

              age = 28    
              # the test condition is always True    
              while age > 19:    
                  print('Infinite Loop')    

              Output:

              Infinite Loop
              Infinite Loop
              Infinite Loop
              Infinite Loop
              Infinite Loop
              Infinite Loop
              Infinite Loop
              ...... and it continues
              

              Explanation:

              In the above example, we created a condition in the while loop that keeps the program in a loop till the age is greater than 19 and assigned the value of the age to 28. As we know that 28 always remains greater than 19, so this condition remains True, which creates an infinite loop. We can exit this infinite loop by forcefully stopping the program or when the memory becomes full.

              Loop Control Statements with Python while Loop

              Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.

              We will now look at various loop control statements used in Python’s while loop.

              1. Break Statement

              The break statement immediately terminates the while loop, regardless of the condition.

              Example

              i = 0    
              while i < 8:    
                  if i == 4:    
                      print("Breaking the loop at", i)    
                      break  # Exits the loop when i is 4    
                  print("Counter is:", i)    
                  i += 1    

              Output:

              Counter is: 0
              Counter is: 1
              Counter is: 2
              Counter is: 3
              Breaking the loop at 4
              

              Explanation:

              In the above example, the loop stops as soon as the counter reaches 4, even though the original condition was counter < 8.

              2. continue Statement

              The continue statement skips the current iteration and moves to the next one without executing the remaining code inside the loop.

              Example

              i = 0  
              while i < 8:  
                  i += 1  
                  if i == 4:  
                      continue  # Skip iteration when i is 4  
                  print("Counter is:", i)  

              Output:

              Counter is: 1
              Counter is: 2
              Counter is: 3
              Counter is: 5
              Counter is: 6
              Counter is: 7
              Counter is: 8
              

              Explanation:

              In the above example, the loop skips the print statement when the counter value is 4; however, it continues executing afterward.

              3. Pass Statement

              The pass Statement acts as a null operator or placeholder. It is applied when a statement is required syntactically, which means that the statement will be visible in the code but will be ignored; hence, it returns nothing.

              Example

              i = 0  
              while i < 8:  
                  if i == 4:  
                      pass  # Placeholder for future logic  
                  print("Counter is:", i)  
                  i += 1  

              Output:

              Counter is: 0
              Counter is: 1
              Counter is: 2
              Counter is: 3
              Counter is: 4
              Counter is: 5
              Counter is: 6
              Counter is: 7
              

              Explanation:

              In this example, the pass statement ensures that Python does not throw an error while we develop the code. Since this function is empty and returns nothing due to the pass statement, there will be no output when we call this function.

              4. Else with a while Loop

              The else block executes after the loop finishes normally (without a break statement).

              Example

              #initializing value of counter to 0  
              counter = 0  
              #using the while loop to iterate the counter up to 7  
              while counter <= 7:  
                  print("Counter is:", counter)  
                  counter += 1  
              #using the else      
              else:  
                  print("Loop completed successfully!")  

              Output:

              Counter is: 0
              Counter is: 1
              Counter is: 2
              Counter is: 3
              Counter is: 4
              Counter is: 5
              Counter is: 6
              Counter is: 7
              Loop completed successfully!
              

              5. Break statement with Else-while Loop

              The Break statement with the else-while loop terminates the program at that very instance when it is executed. In this case, the loop terminates immediately, and the else block is skipped.

              Example

              i = 0  
              while i < 8:  
                  print("Counter is:", i)  
                  if i == 4:  
                      break  # Loop exits early  
                  i += 1  
              else:  
                  print("Loop completed successfully!")  # This won't execute  

              Output:

              Counter is: 0
              Counter is: 1
              Counter is: 2
              Counter is: 3
              Counter is: 4
              

              Explanation:

              In this example, the else block does not execute as the break statement stops the loop early.

              Advantages of the while Loop in Python

              There are several advantages of the while loop in Python. Some of them are as follows:

              1. Easily Executable

              A while loop is one of the best loops in conditions when the number of iterations is unknown, since it runs as long as the condition is True.

              2. An effective loop for User Input Programs

              It is helpful when the loop’s duration is provided by user input.

              3. Prevents Code Duplication

              By handling several iterations quickly, a while loop avoids the need to write repeated code and makes the code easier to understand and maintain.

              4. Allow Infinite Loops

              Infinite loops using True can be helpful in applications like servers, real-time monitoring, and background processes if correctly managed.

              5. Conditional Logic

              The loop can be readily combined with logical conditions to control program flow because it operates on a condition dynamically.

              Disadvantages of While Loop in Python

              There are several disadvantages of while loop in Python. Some of them are as follows:

              1. Risk of Infinite Loops

              The program might get into an endless loop that results in freezing or overuse of the CPU if the loop condition never turns False.

              2. Condition Handling Must Be Done by Hand

              A while loop needs manual condition management, and there is the possibility of raising errors.

              3. Less Readable

              Loops can occasionally be more difficult to read and debug than other loops, particularly when complicated conditions are included.

              4. Overhead in Performance

              When compared to more structured loops, loops might slow down performance by causing unnecessary iterations if they are not appropriately optimized.

              If not done carefully, using break and continue instructions inside while loops can make the code more difficult to read and debug.

              Conclusion

              In the conclusion, Python’s While Loop is used to repeatedly execute a block of code as long as a given condition remains True. It is useful when the number of iterations is unknown beforehand. The While loop can be utilized by using the while keyword and a colon(:).

            1. Python for Loop

              The ‘for’ loop in Python allows us to iterate over iterable objects, such as tuples, lists, dictionaries, and strings, until it reaches the termination of the sequence or the condition is fulfilled. The ‘for’ loop proceeds to the next step after each iteration is completed.

              Syntax of the Python for Loop

              It has the following syntax:

              # syntax of for loop  
              
              for var_name in sequence:  
              
                  # lines of code  
              
                  # to be executed 

                Parameter(s):

                • var_name: A name of a variable assigned to each element in the given sequence.
                • sequence: Sequence refers to iterable elements such as lists, tuples, dictionaries and strings.

                Simple Python for Loop Example

                Let us see through a simple example to understand how the For Loop works in Python.

                Example

                # printing numbers using for loop  
                for i in range(1,7): #Here we have used for loop  
                    print (i)   

                Output:

                1
                2
                3
                4
                5
                6
                

                Explanation:

                In the above example, we used a for loop with the range() function to print numbers ranging from 1 to 6.

                Flowchart of the for Loop in Python

                The following flowchart represents the working of a ‘for’ loop:

                Step 1: The ‘for’ loop iterates over each item in the sequence.

                Step 2: It will check whether the last item in the sequence has been reached; if not, the loop will return to the statement.

                Step 3: If the final item in the sequence is reached, the loop will exit.

                Examples of Python for Loop

                We will now look at some basic examples of Python for loop:

                Printing Elements from a List or Tuple

                Lists and Tuples are the data structures used in Python to store multiple items in a single variable. We can use the ‘for’ loop to iterate through each element of these sequential data structures.

                Let us take a look at the following example:

                Example

                # given list  
                cars = ["Tata", "Honda", "Mahindra", "Suzuki", "BMW"]  
                # using for loop to iterate each element from the list  
                for brands in cars:  
                  print(brands) # printing elements  

                Output:

                Tata
                Honda
                Mahindra
                Suzuki
                BMW
                

                Explanation:

                In this example, we are given a list. We used the ‘for’ loop to iterate through element of the list and printed them.

                Python Program to Print Factorial of a Number

                We will now take a look at an example to print the factorial of a number. For this Python program, we will use the ‘for’ loop to iterate through each number from 1 to that number and add them to return the factorial of the number.

                Example

                # taking input from the user  
                num = int(input("Enter a Number: "))  
                  
                # initializing the initial factorial  
                fact = 1  
                  
                # base cases  
                if num < 0:  
                    # factorial not defined for number less than 0  
                    print("Not Defined!")  
                elif num == 0 and num == 1:  
                    # factorial = 1 for number equal to 0 and 1  
                    print(f"{num}! = {fact}")  
                else:  
                    # using the for loop to iterate from   
                    for i in range(2, num + 1):  
                        # multiplying the current value with the factorial  
                        fact = fact * i  
                      
                    # printing the factorial of the number  
                    print(f"{num}! = {fact}")   

                Output:

                Enter a Number: 5
                5! = 120
                

                Explanation:

                In this example, we have used the ‘for’ loop to iterate through the range from 2 to that number and multiply the value from the current iteration with the initialized factorial value. As a result, we calculated the factorial of the number.

                Nested for Loop

                In Python, a nested ‘for’ loop refers to a ‘for’ loop placed inside the body of another ‘for’ loop. We generally use this structure while iterating over multi-dimensional data structures, generating patterns, or performing operations that requires multiple levels of iteration.

                Syntax:

                Nested for loop has the following syntax:

                for outer_var in outer_iterable:  
                
                    for inner_var in inner_iterable:      
                
                        # Code to be executed in the inner loop  
                
                    # Code to be executed in the outer loop (after the inner loop completes)

                Let us now take a look at some examples to understand the working of nested for loop.

                Printing the Elements of the Matrix

                We will now see an example to print the elements of a 3×3 Matrix using the nested for loop.

                Example

                # given matrix  
                matrix_3x3 = [  
                    [13, 4, 27],   
                    [22, 16, 8],  
                    [5, 11, 19]  
                    ]  
                  
                print("Given Matrix:")  
                # using nested for loop to iterate through each element of the matrix  
                for row in matrix_3x3:  
                  for col in row:  
                    print(col, end = ' ')  
                  print()  

                Output:

                Given Matrix:
                13 4 27
                22 16 8
                5 11 19
                

                Explanation:

                In the above example, we are given a 3×3 matrix. We used the nested for loop to iterate through the rows and columns in the given matrix and print the elements.

                Pyramid Pattern using Nested for Loop

                We will now take a look at the following program to create a Pyramid using the Nested for Loop.

                Example

                row = int(input("Enter number of rows: "))  
                  
                for i in range(1, row + 1):  
                    # Print spaces  
                    for j in range(row - i): #nested loop used  
                        print("  ", end="")  
                      
                    # Print stars  
                    for stars in range(2 * i - 1):  
                        print("* ", end="")  
                      
                    print()  

                Output:

                Enter number of rows: 5
                *
                * * *
                * * * * *
                * * * * * * *
                * * * * * * * * *
                

                Explanation:

                In this example, we are have created a star pyramid using the nested for loop.

                Loop Control Statements with Python for Loop

                We will now look at various loop control statements used in Python’s for loop.

                1) break Statement

                The ‘break’ statement in the ‘for’ loop permanently stops the current iteration.

                Example

                cars = ["Tata", "Honda", "Mahindra", "BMW"]  
                
                for brand in cars:  
                
                  if brand == "Mahindra":  
                
                    break # This break statement will stop iteration  
                
                  print(brand)

                Output:

                Tata
                Honda
                

                Explanation:

                In the above example, we used the break statement in the ‘for’ loop to stop the iterations when the current iteration value is “Mahindra”.

                2) continue Statement

                The ‘continue’ statement in the ‘for’ loop skip the current iteration and move to the next.

                Example

                cars = ["Tata", "Honda", "Mahindra", "BMW"]  
                for brands in cars:  
                  if brands == "Mahindra":  
                    continue # this statement will stop iteration if Mahindra occurs, continue further  
                  print(brands)  

                Output:

                Tata
                Honda
                BMW
                

                Explanation:

                In this example, we used the continue statement to skip the current iteration of the ‘for’ loop.

                3) pass Statement

                In ‘for’ loop, the ‘pass’ statement in Python is used as a placeholder. It means that we can use it when we need to write something in our code but don’t want it to do anything or want to leave space to write something in the future.

                Example

                for n in range(1, 11):  
                  if n % 3 == 0:  
                      pass # this works as a placeholder  
                  else:  
                      print(n)  

                Output:

                1
                2
                4
                5
                7
                8
                10
                

                Explanation:

                In this pass statement in for loop example, the pass statement is a placeholder indicating that a piece of code can be added in the if-block in the future.

                4) else with for loop

                The ‘else’ statement in the ‘for’ loop is used to provide an output when the previous condition is not met or cannot be achieved.

                Example

                for i in range(1, 10):  
                  print(i)  
                else:  
                  print("Loop Finished")  

                Output:

                1
                2
                3
                4
                5
                6
                7
                8
                9
                Loop Finished
                

                Explanation:

                In this example, the else statement is execute after the completion of the ‘for’ loop.

                Conclusion

                The ‘for’ Loop in Python is a very crucial construct in the programming world, which helps in various aspects such as iteration and looping. Control statements like continue, break, pass and else make the functioning of the program more controlled and efficient.

              1. Python Loops

                Python loops are control flow structures that allow us to execute a block of code repeatedly. Python provides two main types of loops – for and while. Additionally, there is support for nested loops in Python, allowing us to loop within loops to perform more complex tasks.

                Python Loops

                While all these loops offer similar basic functionality, they differ in their syntax and condition-checking time.

                For Loop in Python

                In Python, we use for loops for sequential traversal. For example, traversing the elements of a string, list, tuple, etc. It is the most commonly used loop in Python that allow us to iterate over a sequence when we know the number of iterations beforehand.

                Python Loops

                Syntax:

                The following is the syntax of Python for Loop:

                for element in given_sequence:  
                
                  # some block of code

                Simple Python for Loop Example

                Let us take a look at a basic implementation of the for loop in Python:

                Example

                # example of a for loop in Python  
                  
                # iterating using for loop  
                for i in range(1, 6):  
                  print(i)  

                Output:

                1
                2
                3
                4
                5
                

                Explanation:

                Here, we have used a for loop to iterate through the numbers ranging from 1 to 5. In each iteration, the current number is stored and printed.

                Iterating over a Sequence using Python for Loop

                We can use for loop to iterate over strings, lists, tuples, and dictionaries in Python, as shown in the following example:

                Example

                # python example to show use of for loop in sequential traversal  
                  
                # given string  
                str_1 = "Learn Python"  
                  
                # iterating over string using for loop  
                for i in str_1:  
                    print(i)  
                  
                print()  
                  
                # given list  
                list_1 = ["Welcome", "to", "Learn", "Python"]  
                  
                # iterating over list using for loop  
                for i in list_1:  
                    print(i)  
                  
                print()  
                  
                # given tuple  
                tuple_1 = ("Python", "for", "Beginners")  
                  
                # iterating over tuple using for loop  
                for i in tuple_1:  
                    print(i)  
                  
                print()  
                  
                # given dictionary  
                dict_1 = {  
                    1: "Learn",  
                    2: "Python"  
                }  
                  
                # iterating over dictionary using for loop  
                for i in dict_1:  
                    print(i, ":", dict_1[i])  

                Output:

                L
                e
                a
                r
                n
                P
                y
                T
                h
                o
                n

                Welcome
                to
                Learn
                Python

                Python
                for
                Beginners

                1 : Learn
                2 : Python

                Explanation:

                In this example, we have used the for loop to traverse different types of sequences such as string, list, tuple, and dictionary.

                Iterating by the Index of Sequence

                In Python, we can also use the index of the elements in the given sequence for iteration. The basic idea for this approach is first to determine the size of the sequence (e.g., list, tuple) and then iterate over it within the range of the determined length.

                Let us take a look at the following example:

                Example

                # python example to iterate over sequence using index  
                  
                # given list  
                fruit_basket = ['apple', 'banana', 'orange', 'mango', 'kiwi']  
                  
                # iterating over the index of elements in the list  
                for i in range(len(fruit_basket)):  
                  # printing the index and the item  
                  print(i, ":", fruit_basket[i])  

                Output:

                0 : apple
                1 : banana
                2 : orange
                3 : mango
                4 : kiwi
                

                Explanation:

                Here, we have used the len() function to determine the length of the given sequence and then used the range() function to generate the index values ranging from 0 to the length of the list minus 1. The for loop then prints both the index and the corresponding element.

                Use of else Statement with Python For Loop

                In Python, we can also use the else statement with the for loop. The for loop does not consist of any condition on the basis of which the execution will stop. Thus, the code inside the else block will only run once the for loop finishes iterations.

                Syntax:

                The syntax of the else statement with Python for loop is shown below:

                for element in given_sequence:  
                
                  # some block of code  
                
                else:  
                
                  # some block of code runs if loop ends without break

                Python for Loop Example using else Statement

                Let us see an example of showing how the else statement works with the for loop in Python.

                Example

                # python example to show use of else statement with for loop  
                  
                # given list  
                fruits = ['guava', 'apple', 'orange', 'mango', 'banana', 'melon']  
                  
                # iterating with for loop  
                for item in fruits:  
                  # inside for block  
                  print(item) # printing items  
                else:  
                  # inside else block  
                  print("Welcome to else Block.") # printing statement  

                Output:

                guava
                apple
                orange
                mango
                banana
                melon
                Welcome to else Block.
                

                Explanation:

                In this example, we have combined the else statement with the for loop. Since the for loop does not have any conditions, it iterated over the entire list and then executed the else block.

                While Loop in Python

                while loop in Python allows us to execute a block of code repeatedly as long as a particular condition evaluates to True. It is usually utilized when the number of iterations is unknown beforehand.

                Python Loops

                Syntax:

                It has the following syntax:

                while given_condition:  
                
                  # some block of code 

                  Python While Loop Example

                  Let us now see a simple example of the while loop in Python.

                  Example

                  # example of a for loop in Python  
                    
                  # initializing a counter  
                  counter = 1  
                    
                  # iterating using while loop  
                  while counter <= 5:  
                    print("Learn Python")  
                    # incrementing counter by 1  
                    counter += 1  

                  Output:

                  Learn Python
                  Learn Python
                  Learn Python

                  Explanation:

                  In this example, we have used the while loop to print a statement five times. We have initialized a counter with an initial value of 1. We then define a condition in the while loop to iterate the loop as long as the counter is less than or equal to 5. Inside the loop statement, we have incremented the counter value by 1.

                  Use of else Statement with Python While Loop

                  Similar to the use of the else statement with the for loop, we can use it with Python while loop. The else block will run only when the loop condition becomes false, implying that the loop terminates normally.

                  Syntax:

                  The syntax of the else statement with Python for loop is shown below:

                  for element in given_sequence:  
                  
                    # some block of code  
                  
                  else:     
                  
                    # some block of code runs if loop ends without break

                  Python else statement Example with While Loop

                  We will now look at the following example to see the use of the else statement with the while loop in Python:

                  Example

                  # python example to show use of else statement with while loop  
                    
                  # given list  
                  fruits = ['guava', 'apple', 'orange', 'mango', 'banana', 'melon']  
                    
                  # initializing a counter  
                  counter = 0  
                    
                  # iterating with while loop  
                  while counter < len(fruits):  
                    # inside for block  
                    print(fruits[counter])  
                    # incrementing counter  
                    counter += 1  
                  else:  
                    # inside else block  
                    print("Welcome to else Block.") # printing statement  

                  Output:

                  guava
                  apple
                  orange
                  mango
                  banana
                  melon
                  Welcome to else Block.
                  

                  Explanation:

                  In this example, we have combined the else statement with the while loop. Since we have not used any break statement, the while loop runs until the given condition becomes false. After that, it will execute the print statement from the else block.

                  Infinite While Loop in Python

                  In Python, we can also create a loop to execute a block of code for infinite times using the while loop, as shown in the following example:

                  Example

                  # python example on infinite while loop  
                    
                  # initializing counter  
                  counter = 0  
                    
                  # iterating using while loop  
                  while counter == 0:  
                    print("Learn Python")  
                    # no increment statement  

                  Output:

                  Learn Python
                  Learn Python
                  Learn Python
                  Learn Python
                  Learn Python
                  ...

                  Explanation:

                  In this example, we have created an infinite while loop. Since the counter is initialized with the value of 0 and the condition counter == 0 always remains true, the loop runs forever, continuously printing the statement.

                  Note: It is suggested not to use this type of loop. It is a never-ending loop where the condition always remains true and we have to terminate the interpreter forcefully.

                  Nested Loops in Python

                  nested loop is a loop inside another loop. In Python, we can nest both for and while loops. Nested loops are useful while working with multi-dimensional data like grids or matrices or while performing certain complex operations.

                  Syntax:

                  The following is the syntax of the Python nested for loop:

                  for outer_var in outer_sequence:  
                  
                    # some block of code in outer loop  
                  
                    for inner_var in inner_sequence:  
                  
                      # some block of code in inner loop  

                    The syntax of the Python nested while loop is given below:

                    while outer_condition:  
                    
                        # some block of code in outer loop  
                    
                        while inner_condition:  
                    
                          # some block of code in inner loop  

                      We can also use one type of loop inside another other type of loop in Python. For example, we can use a while loop inside a for loop or vice versa.

                      Python Nested Loop Example

                      Let us see an example of a Python nested loop.

                      Example

                      # python example to print a pattern using nested loop  
                        
                      # iterating using for loop  
                      for i in range(1, 11):  
                        # iterating using nested for loop  
                        for j in range(1, i + 1):  
                          # printing pattern  
                          print("*", end=" ")  
                        # new line  
                        print()  

                      Output:

                      *
                      * *
                      * * *
                      * * * *
                      * * * * *
                      * * * * * *
                      * * * * * * *
                      * * * * * * * *
                      * * * * * * * * *
                      * * * * * * * * * *
                      

                      Explanation:

                      In this example, we use a nested for loop to print “*” multiple times in each row, where the number of times it prints increases with each iteration of the outer loop (based on the value of i).

                      Loop Control Statements in Python

                      In Python, we use loop control statements in order to change the sequence of execution. Once the execution leaves a scope, the objects created in the same scope are also destroyed automatically.

                      Python offers support for the following control statements:

                      Loop Control StatementDescription
                      ContinueIt returns the control to the beginning of the loop
                      BreakIt terminates the loop immediately, even if the condition or sequence is not finished.
                      PassIt acts as a placeholder that does nothing.

                      Let us take a look at the following example demonstrating the use of these control statements in Python.

                      Example

                      # python example to show the use of different loop control statements  
                        
                      print("Example with continue statement:")  
                      for i in range(1, 6):  
                        if i == 3:  
                          # continue statement  
                          continue  # Skip the iteration when i is 3  
                        print(i)  
                        
                      print("\nExample with break statement:")  
                      for i in range(1, 6):  
                        if i == 4:  
                          # break statement  
                          break  # Exit the loop when i is 4  
                        print(i)  
                        
                      print("\nExample with pass statement:")  
                      for i in range(1, 4):  
                        if i == 2:  
                          # pass statement  
                          pass  # Do nothing when i is 2  
                        else:  
                          print(i)  

                      Output:

                      Example with continue statement:
                      1
                      2
                      4
                      5
                      
                      Example with break statement:
                      1
                      2
                      3
                      
                      Example with pass statement:
                      1
                      3
                      

                      Explanation:

                      In this example, we have used the different loop control statements. The continue statement is used to skip the iteration when i = 3, so 3 is not printed. The break statement is used to terminate the loop when i = 4. The pass statement here did nothing and simply acted as a placeholder.

                      Conclusion

                      In this tutorial, we learned about loops in Python. We understand how loops act as an essential part of programming to automate repetitive tasks and to iterate over sequences like strings, lists, or ranges. Python provides mainly two types of loops – for and while, along with control statements like continue, break, and pass that help us to write flexible and efficient code.

                    1. Python if-else Statements

                      In Python, conditional statements are the statements that allow a program to make decisions based on conditions. These statements enable the execution of different blocks of code relying on whether a condition is True or False.

                      Types of Conditional Statements in Python

                      Python provides support for the following types of conditional statements:

                      1. if statement
                      2. if-else statement
                      3. Nested if statement
                      4. if-elif-else statement

                      Let us discuss these conditional statements in detail.

                      if Statement

                      Programs execute the code inside the if block when the condition evaluates as True.

                      Python If-else statements

                      This represents the simplest decision-making construct. Programs can determine dynamic responses through the if statement because it activates specific actions based on defined conditions.

                      Syntax:

                      It has the following syntax:

                      if condition:  
                      
                          # Code to execute if condition is True

                        Simple Python if Statement Example

                        Let us consider a simple example showing the implementation of if statement in Python:

                        Example 1

                        # initializing the age  
                        age = 18  
                          
                        # if statement: checking if the given age is greater than or equal to 18  
                        if age >= 18:  
                          # printing a message  
                          print("You are eligible to vote.")  # This executes because the condition is True  

                        Output:

                        You are eligible to vote.

                        Explanation:

                        Through an if statement the provided Python code determines voting eligibility for individuals. The program evaluates the age condition against 18. Execution of the indented block occurs because age is 18 thus making the condition True which results in printing “You are eligible to vote.” When age falls below 18 the condition becomes False which causes the print statement to omit. Python requires indentation because it serves to mark the sections of code that will execute whenever the specified condition meets the requirement.

                        Let us now consider another example, where the program will return a message according to the entered age of the user:

                        Example 2

                        # asking age from the user  
                        age = int(input("Enter your age: "))  
                          
                        # multiple if blocks  
                        if age < 18: # checking if age is less than 18  
                            # printing a message  
                            print("You are not eligible to vote")  
                          
                        if age >= 18: # checking if age is greater than or equal to 18  
                            # printing a message  
                            print("You are eligible to vote.")  
                          
                        if age >= 21: # checking if age is greater than or equal to 21  
                            # printing a message  
                            print("You are allowed to consume alcohol in some countries.")  
                          
                        if age >= 60: # checking if age is greater than or equal to 60  
                            # printing a message  
                            print("You are eligible for senior citizen benefits.")  
                          
                        if age >= 80: # checking if age is greater than or equal to 80  
                            # printing a message  
                            print("You are a very senior citizen. Take extra care of your health.")  

                        Output:

                        # Output 1:
                        Enter your age: 20
                        You are eligible to vote.
                        # Output 2:
                        Enter your age: 65
                        You are eligible to vote.
                        You are allowed to consume alcohol in some countries.
                        You are eligible for senior citizen benefits.
                        

                        Explanation:

                        Multiple independent if statements appear within the Python program to verify various conditions according to the user-entered age. An if statement works separately from other if statements which enables two or more conditions to satisfy simultaneously.

                        The if statements function independently of one other because they remain isolated from each other. The program becomes dynamic and flexible because the execution includes all corresponding code blocks whenever multiple conditions become true.

                        if…else Statement

                        Programming contains the if…else statement as its core element for making decisions in code execution. One block of code executes through the if statement when conditions prove true, but a different block activates with conditions evaluated false.

                        Python If-else statements

                        Different actions will follow according to different conditions because of this structure. The if block examines a condition while true results activating the block of code; otherwise, the else block executes.

                        The structure of if…else statement works as a valuable tool for managing two possible results from a condition which enhances the program flexibility and responsiveness. A programming language requires either indentation or brackets to display code blocks in a clear manner.

                        Syntax:

                        Here is the syntax for the if…else statement.

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

                        Python if-else Statement Example

                        Let us a simple example showing the implementation of the if…else statement in Python:

                        Example

                        # asking age from the user  
                        age = int(input("Enter your age: "))  
                          
                        # if-else statement: checking whether the user is eligible to vote or not  
                        if age >= 18:  
                          # if block  
                          print("You are eligible to vote.")  
                        else:  
                          # else block  
                          print("You are not eligible to vote.")  

                        Output:

                        # Output 1:
                        Enter your age: 20
                        You are eligible to vote.
                        # Output 2:
                        Enter your age: 16
                        You are not eligible to vote.
                        

                        Explanation:

                        The Python program utilizes an if…else construct to verify voter eligibility status of users. Before proceeding the program obtains an integer age from the user. The if statement confirms whether the entered age exceeds 18 years. The program displays “You are eligible to vote” when the specified condition turns out true. Because the condition evaluates to false which indicates an age lower than 18 years old the program proceeds to display “You are not eligible to vote.” Through this method the program generates the proper response whenever a user fits into either condition.

                        The if…else construct serves programs that need decisions between two outcomes because it enables proper output selection according to user input. A coding error will occur in Python if you do not use indentation to specify your code blocks.

                        Nested if…else statement

                        A nested if…else statement places an if…else block within both if statements and else statements. A program is then able to perform advanced decision-making through this structure by allowing multiple tests of conditions.

                        Python If-else statements

                        The first step evaluates the outer if condition. The nested control block executes the if or else sections depending on newly introduced conditions when the first if condition returns true. The block serves efficient decision-making operations that use various conditions.

                        In Python, the correct indentation stands as the main indicator of nested blocks although other coding languages use curly braces {} to define these structures. The if…else block within an if…else block simplifies execution in applications involving user authentication and grading systems and order processing.

                        The use of conditional blocks requires caution since their excessive application can generate code that becomes unreadable but also remain difficult to maintain code clarity and code efficiency.

                        Syntax:

                        Here is the syntax for a nested if…else statement.

                        if condition1:  
                        
                            if condition2:  
                        
                                # Code to execute if both condition1 and condition2 are True  
                        
                            else:  
                        
                                # Code to execute if condition1 is True but condition2 is False  
                        
                        else:  
                        
                            # Code to execute if condition1 is False

                        Programs can check multiple conditions in an organized order through a nesting structure of if else statements.

                        First, condition1 is evaluated. The program enters the first if block because condition1 evaluates as true before checking condition2. Both the first and second condition evaluations lead to program execution of their associated blocks. The program will execute the else block within the first if when condition2 proves to be false.

                        The outer else block runs directly when condition1 remains false after the initial evaluation. The practice delivers practical benefits for determining decisions that rest on multiple preconditions like user verification and complex business rule processing or multiple structured constraints. Every Python program requires correct indentation to ensure clear program representation.

                        Python Nested if-else Statement Example

                        Let us consider an example showing the implementation of the nested if…else statement in Python.

                        Example 1

                        # asking user to enter password  
                        password = input("Enter your password: ")  
                          
                        # nested if-else statement: checking whether the password is strong or not  
                        if len(password) >= 8:  # checking the length of the password  
                          # outer if block  
                          if any(char.isdigit() for char in password): # checking if the password consists of any numeral value  
                            # inner if block  
                            print("Password is strong.")  
                          else:  
                            # inner else block  
                            print("Password must contain at least one number.")  
                        else:  
                          # outer else block  
                          print("Password is too short. It must be at least 8 characters long.")  

                        Output:

                        # Output 1:
                        Enter your password: secure123
                        Password is strong.
                        # Output 2:
                        Enter your password: password
                        Password must contain at least one number.

                        Explanation:

                        The program evaluates user password strength through a conditional if else structure nested inside another if else block. As a first step the program requires a password as input from the user. The program first examines whether the length of the entered password is 8 characters or more through this outer if statement. The inner if statement uses the any() function to validate that the password has a numeric digit when run successfully. The program displays “Password is strong” when a digit exists in the input. The program displays “Password must contain at least one number” through the nested else clause when a password does not contain at least one number. The outer else section executes because the entered password consists of fewer than 8 characters.

                        Through this evaluation method the system examines both password length requirements as well as password complexity to ensure proper security standards. Indentation across the codebase supports easy reading in Python programming language.

                        Let us see another example showing the working of the nested if…else statement in Python:

                        Example 2

                        # asking user to enter their marks  
                        marks = int(input("Enter your marks: "))  
                          
                        # nested if-else statement: checking if the user passed with distinction or not  
                        if marks >= 40: # checking if the user got marks greater than or equal to 40  
                          # outer if block  
                          if marks >= 75: # checking if the user got marks greater than or equal to 75  
                            # inner if block  
                            print("Congratulations! You passed with distinction.")  
                          else:  
                            # inner else block  
                            print("You passed the exam.")  
                        else:  
                          # outer else  
                          print("You failed the exam. Better luck next time.")  

                        Output:

                        # Output 1:
                        Enter your marks: 80
                        Congratulations! You passed with distinction.
                        # Output 2:
                        Enter your marks: 35
                        You failed the exam. Better luck next time.
                        

                        Explanation:

                        A nested if else structure in the program establishes passing or failing criteria which depends on student marks. The program starts by accepting student marks as an integer value. First the outer if clause examines if the marks exceed 40 which indicates passing status. The program uses the inner if condition to confirm if marks exceed 75. If so, it prints “Congratulations! You passed with distinction.” The code inside the inner else block runs when the marks are higher than 40 but less than 75 so the message “You passed the exam” appears. When student marks fall below 40 the outer else statement activates to display “You failed the exam. Better luck next time.” The structured system functions to split student academic results into separate categories for better assessment.

                        if…elif…else Statement

                        A program requires the if…elif…else statement to evaluate sequential conditions for multiple tests. A program can check several conditions in succession to locate a condition which produces a True outcome.

                        Python If-else statements

                        The first step checks the if condition because it determines if the corresponding code block needs execution before moving to the next elif conditions. An if statement will be evaluated when all previous conditions prove false. A match of any elif condition results in program execution of its associated code thus skipping all following conditions. The execution path ends at the else block whenever none of the conditions are satisfied. The decision structure provides efficient outcome management for software with numerous possible results.

                        Syntax:

                        Here is the syntax for an if…elif…else statement.

                        if condition1:  
                        
                            # Code to execute if condition1 is True  
                        
                        elif condition2:  
                        
                            # Code to execute if condition2 is True  
                        
                        elif condition3:  
                        
                            # Code to execute if condition3 is True  
                        
                        else:  
                        
                            # Code to execute if none of the conditions are True

                        Multiple conditions within a program requires an if…elif…else structural evaluation process.

                        The program first checks condition1. When one of the if condition meets the truth requirement, then the attached code runs before breaking off from the entire set of conditions.

                        The program proceeds to evaluate condition2 only after condition1 becomes false. The code block for condition2 will execute when it meets the truth criterion.

                        The program relocates to check condition3 only when both condition1 and condition2 prove to be false. By default, the else block runs when all previous conditions turn out to be untrue.

                        The structure prevents decision-making complexity by executing only single block from multiple if statements when the first condition becomes true.

                        Pythin if-elif-else Statement Example

                        Let us consider an example showing the implementation of the if…elif…else statement in Python.

                        Example 1

                        # asking user to enter temperature  
                        temperature = int(input("Enter the temperature in Celsius: "))  
                          
                        # if-elif-else statement: checking temperature  
                        if temperature >= 30: # if temperature is greater than or equal to 30 deg  
                          # if block  
                          print("It's a hot day.")  
                        elif temperature >= 20: # if temperature is greater than or equal to 20 deg  
                          # elif block  
                          print("The weather is warm.")  
                        elif temperature >= 10: # if temperature is greater than or equal to 10 deg  
                          # another elif block  
                          print("It's a cool day.")  
                        else: # if temp is less than 10 deg  
                          # else block  
                          print("It's a cold day.")  

                        Output:

                        # Output 1:
                        Enter the temperature in Celsius: 35
                        It's a hot day.
                        # Output 2:
                        Enter the temperature in Celsius: 22
                        The weather is warm.
                        

                        Explanation:

                        The program uses an effective system which groups temperature zones, so a single condition runs for provided inputs. The evaluation procedure follows a sequence to make better decisions which eliminates avoidable tests. This program helps users obtain weather conditions immediately through its applications which depend on weather conditions. The program allows future development to integrate detailed temperature categories and specific alert messages. Python’s syntax with indentation helps maintenance teams understand the program logic more easily. Through its form structure the system enables applications to automate weather alerts and clothing recommendations and climate-based planning. Temperature threshold modifications allow this program to operate across various climate zones thus defining its status as a flexible practical forecast system.

                        Here is another example of an if…elif…else statement that categorizes exam grades based on marks.

                        Example

                        # asking user to enter their marks  
                        marks = int(input("Enter your marks: "))  
                          
                        # if-elif-else statement: grading marks  
                        if marks >= 85: # if marks is greater or equal to 90, printing A  
                          print("Grade: A")  
                        elif marks >= 65: # if marks is greater or equal to 80, printing B  
                          print("Grade: B")  
                        elif marks >= 50: # if marks is greater or equal to 70, printing C  
                          print("Grade: C")  
                        elif marks >= 33: # if marks is greater or equal to 60, printing D  
                          print("Grade: D")  
                        else: # if marks is less than 90, printing F  
                          print("Grade: F")  

                        Output:

                        # Output 1:
                        Enter your marks: 95
                        Grade: A
                        # Output 2:
                        Enter your marks: 64
                        Grade: C
                        

                        Explanation:

                        Through its if…elif…else structure the program receives student marks followed by grade assessment. It first converts the input into an integer. The first conditional statement verifies whether the marks reach or exceed 85 points. The program displays “Grade: A” when the statement evaluates to true. It will display “Grade: B” if the marks exceed 65 while failing the previous if condition. Under the second elif statement the code verifies whether the student received marks between 50 and 64 to display “Grade: C.” The program uses another elif condition to evaluate marks that exceed 33 before printing “Grade: D.” The program executes the else block and displays “Grade: F” if all previous conditional criteria fail to match. The structure allows the program to match one single condition and evaluate the appropriate grade according to mark levels.

                        Conclusion

                        Decision-making forms an essential programming principle because it allows programs to activate specific code through established conditions. The programming language contains multiple conditional statements composed of if, if…else, nested if…else and if…elif…else structures to execute conditions in an efficient manner.

                        Python requires proper indentation because it enables readable code and prevents syntax errors in the program. Program dynamicity together with interaction become possible through the use of decision-making statements which enhance code efficiency. Programmers who learn these programming principles develop the ability to construct efficient logical structured applications for real-life systems which automate multiple computational procedures accurately.