Python | Loops | While Loop

A while loop will execute a block of code until a predefined condition is met.

Here is an example:

count_up = 1
while (count_up <= 3):
	print 'Starting in:', count_up
	count_up += 1
print "GO!"

The code says that the variable count_up has a value of 1. After that the conditions start. As long as the variable count_up has a value of 3 or less than 3, the message Starting in: count_up(the value of count_up at that moment) will be printed on the screen.

Next the code tell count_up to increase by 1. When the code finishes to execute the while loop it will print “GO!”.

while loop Python

You can modify the code to count down.

count_down = 3
while (count_down > 0):
	print 'Starting in:', count_down
	count_down -= 1
	# the below line is also valid
	# count_down = count_down - 1
print "GO!"

It works just like the first piece of code but it goes backwards, it counts down.

while loop Python

The next example keeps slicing off the first character of a string until the string is empty
and hence false.

>>> name = 'dumitrache'
>>> while name:
...     print(name, end = ' | ')
...     name = name[1:]
... 
dumitrache | umitrache | mitrache | itrache | trache | rache | ache | che | he | e | >>>
  • While name is not empty
  • print name
  • Strip first character off name

Note :
The end = ' | ' keyword argument used here to place all outputs on the same line
separated by a separator.

The following code counts from the value of a up to, but not including, b.

>>> a = 0
>>> b = 5
>>> while a < b:
...     print(a, end = ' ')
...     a += 1
... 
0 1 2 3 4 >>> 

Leave a Reply