Sometimes, you may need to use a looping structure in your Python code, but only want to execute the loop once. In this post, we will show you how to run a loop only once in Python using a for loop or a while loop. Here is a complete example of using a for loop to print a message only once in Python:
Run a For Loop only Once in Python Example
In the below example, we are using a for loop to iterate over a range of numbers from 0 to 1 (inclusive). Since we only want the loop to run once, we use the range function to specify a range of 1 number. This means that the loop will only execute once. Inside the loop, we have a single print statement that will print the message "This message will only be printed once."
for i in range(1): print("This message will only be printed once.")
Output:
This message will only be printed once.
And here is a complete example of using a while loop with a break statement to achieve the same result:
In this example, we are using a while loop with a True condition. This means that the loop will run indefinitely, until we use a break statement to exit the loop. Inside the loop, we have a single print statement that will print the message "This message will also only be printed once." After the print statement, we use a break statement to exit the loop. This means that the loop will only run once, since it will immediately exit after the first iteration.
while True: print("This message will also only be printed once.") break
Output:
This message will also only be printed once.