Scripting

Python While Loop

Python While Loop

Introduction

while loop in python is used to execute a particular piece of code over and over. It will repeat until the condition you set is satisfied. The line immediately after the loop will be executed if the condition becomes false. while loop is of indefinite iteration.

And we will guide you on how to use the while loop in Python as we did below. Hope you understand.

Example

i = 2

while i <= 8:

print(i)

i += 2

Output:

2

4

6

8

Definition

The while loop will loop until the condition you set is satisfied.

If the condition becomes false, the line after loop will be executed.

while loop with break statement

break still stops the loop even though the condition is true.

Example 1: Stop the loop when i = 6

i = 2

while i <= 8:

print(i)

if i == 6:

break

i += 2

Output:

2

4

6

More example

Example : Sum the numbers

print("Enter the ending number: ")

n = int(input())

sum = 0

i = 1

while i <= n:

sum += i

i += 1

print("Sum =",sum)

Output:

Enter the ending number: 3

Sum = 6

Conclusion

We have shown you how to use the while loop in Python.

Thanks for referring!

Similar Posts