Friday, September 5, 2025
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

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS