Python while loop

In computer programming, a loop is a programming structure that repeats a sequence of instructions until a specific condition is met. Python has various types of loops, while loop is one of them. In this Python tutorial section, you will learn about while loop.


Objectives

  • Basic understanding of Python while loop

  • Else in Python While Loop


Basic understanding of Python while loop

Syntax

while expression:
    statement(s)

Code

# While loop
start_count = 1
end_count = 6
while start_count <= end_count:
    print(start_count)
    start_count += 1

Output

1
2
3
4
5
6

Process finished with exit code 0

Here, start_count = 1 is the starting point of the loop and end_count = 6 define end of the task, while start_count <= end_count here by while loop checking start_count less than or equal to end_count if it less than then the codes are executed inside the loop else not. start_count += 1 every time it increase the start_count value by 1. Remember to increment start_count, or else the loop will continue forever.


Else in Python While Loop

With the else statement you can run a block of code once when the condition no longer is true

Syntax

while expression:
    statement(s)
else:
    something

Code

# While loop with else
start_count = 1
end_count = 6
while start_count <= end_count:
    print(start_count)
    start_count += 1
else:
    print("Loop completed")

Output

1
2
3
4
5
6
Loop completed


Python while loop video tutorial