Python While Loop with code samples
Much like a Java while loop, you can use a Python while loop to repeatedly execute a block of code as long as a condition is true. In this article, we will learn more about the Python while loop. Python While loop Syntax A while loop in Python has the following syntax: while <condition>: loop body The while keyword is followed by a condition. If the condition evaluates to true, the body of the loop is executed. Once the body of the loop is completed, the condition is checked again and this is repeated until the condition evaluates to false at which point the loop is exited. While loop Sample Code The following code demonstrates how you can use the while loop: num=10counter=1total=0while counter<=num: total += counter counter+=1print("sum of first 10 numbers is",total) This code adds the numbers from 1 to 10 and prints the sum. It uses a while loop to iterate from 1 to 10. The while loop checks the condition counter <= num and if so adds the current value of count