Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to use while True in Python

How to use while True in Python

In this article, we will discuss how to use while True in Python.

While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever.

Example: While Loop with True

Python3




# Python program to demonstrate
# while loop with True
  
while True:
    pass


If we run the above code then this loop will run infinite number of times. To come out of this loop we will use the break statement explicitly.

Let’s consider the below example, where we want to find the sum of the first N numbers. Let’s see the below code for better understanding.

Example: While Loop with True to find the sum of first N numbers

Python3




# Python program to demonstrate
# while loop with True
  
N = 10
Sum = 0
  
# This loop will run forever
while True:
    Sum += N
    N -= 1
      
    # the below condition will tell
    # the loop to stop
    if N == 0:
        break
          
print(f"Sum of First 10 Numbers is {Sum}")


Output

Sum of First 10 Numbers is 55

In the above example, we have used the while True statement to run the while loop and we have added an if statement that will stop the execution of the loop when the value of N becomes 0 If we do not write this if statement then the loop will run forever and will start adding the negative values of N to the sum.

RELATED ARTICLES

Most Popular

Recent Comments