PYTHON while LOOPS
You can define a while loop to iterate through a set of numbers, as shown in the following examples:
>>> x = 0 >>> while x < 5: ... print(x) ... x = x + 1 ... 0 1 2 3 4 5
Python uses indentation instead of curly braces that are used in other languages such as JavaScript and Java. Although the Python list data structure is not discussed until later in this chapter, you can probably understand the following simple code block that contains a variant of the preceding while loop that you can use when working with lists:
lst = [1,2,3,4]
while lst:
print('list:',lst)
print('item:',lst.pop())
The preceding while loop terminates when the lst variable is empty, and there is no need to explicitly test for an empty list. The output from the preceding code is here:
list: [1, 2, 3, 4] item: 4 list: [1, 2, 3] item: 3 list: [1, 2] item: 2 list: [1] item: 1
This concludes the examples that use the split() function in order to process words and characters in a text string. The next part of this chapter shows you examples of using conditional logic in Python code.