How to use while True in Python
Last Updated :
22 Nov, 2021
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
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
N = 10
Sum = 0
while True :
Sum + = N
N - = 1
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.
Please Login to comment...