Open In App

How to Emulate a Do-while loop in Python?

We have given a list of strings and we need to emulate the list of strings using the Do-while loop and print the result. In this article, we will take a list of strings and then emulate it using a Do-while loop.

Do while loop is a type of control looping statement that can run any statement until the condition statement becomes false specified in the loop. In do while loop the statement runs at least once no matter whether the condition is false or true.

Example:

Input : ["geeksforgeeks", "C++", "Java", "Python"]
Output: geeksforgeeks
C++
Java
Loop has exited.
Explanation : Here, we take a string of list as input and emulate the list using Do-while loop.

How to Emulate a Do-while loop in Python?

Below, are the methods to Emulate a Do-while loop in Python.

Emulate a Do-while loop Using a Conditional Break

In this example, the below code creates a list of strings and enters an infinite loop. Within the loop, it prints each string from the list once. It then breaks out of the loop and prints a message confirming the loop has exited.

# Example list of strings
strings_list = ["geeksforgeeks", "C++", "Java", "Python", "C", "MachineLearning"]

# Start the loop
while True:
  
    # Code block to execute at least once
    print("Strings in the list:")
    for string in strings_list:
        print(string)
    
    # Exit the loop
    break

# Code block outside the loop
print("Loop has exited.")

Output
Strings in the list:
geeksforgeeks
C++
Java
Python
C
MachineLearning
Loop has exited.

Emulate a Do-while loop Using a Flag Variable

In this example, below code starts by printing a message indicating that it's going to display the strings in the list. It then employs a while loop with a flag variable to iterate over each string in the list and print it. The loop continues until the index exceeds the length of the list, at which point the flag is set to False, and the loop terminates.

# Example list of strings
strings_list = ["geeksforgeeks", "C++", "Java", "Python", "C", "MachineLearning"]

print("Strings in the list:") 

# Using a while loop with a flag variable
flag = True
index = 0
while flag:
  
    # Execute the code block at least once
    current_string = strings_list[index]
    print(current_string)
    
    # Increment the index
    index += 1
    
    # Set the flag to False if the loop should terminate
    if index >= len(strings_list):
        flag = False
        
# Code block outside the loop
print("Loop has exited.")

Output
Strings in the list:
geeksforgeeks
C++
Java
Python
C
MachineLearning
Loop has exited.
Article Tags :