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!”.
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.
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 | >>>
nameis not empty
- Strip first character off
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,
>>> a = 0 >>> b = 5 >>> while a < b: ... print(a, end = ' ') ... a += 1 ... 0 1 2 3 4 >>>