Loops


for loops

In last week's introduction about data types, we already had a first glance at for loops. Remember this image:


Source: https://www.tutorialspoint.com

In Python, the start and end of a for loop – and, for that matter, of any other control structure and function definition – is defined by indentation rather than curly brackets ({}), as would be the case, for example, in C++ and R. Here, the basic syntax looks as follows:

for item in sequence :
   indentedStatement to repeat, can use item

And here's a more practical example:


In [1]:
for i in [0, 1, 2, 3]:
    print(i)


0
1
2
3

The utilized indent does not necessarily have to be a single tab stopp (\t, i.e. four digits) in length, as shown in the above code chunk, but any number of digits larger than zero. For example, a 2-digit spacing would be fine as well:


In [2]:
for i in [0, 1, 2, 3]:
  print(i)


0
1
2
3

However, since most IDEs default to a tab-delimited indent, and moreover, for us to keep things a little more concise, we are going to stick to a 4-digit indent from here on out.

As you may have noticed, for loops expect the sequence of items to loop over to be provided as an object of


In [3]:
type([0, 1, 2, 3])


Out[3]:
list

One last thing before moving on to our first hands-on session about for loops:

Instead of directly supplying a sequence of numbers (in our case, [0, 1, 2, 3]), we could have also created a list variable and passed it on to the loop construct. Such an approach might come in particularly handy when working with larger lists, as in doing so, we could simply use Python's range() function to loop over the length of our input sequence, and hence, extract each corresponding value at the i-th position.


In [4]:
x = [0, 1, 2, 3]

for i in range(len(x)):
    print(x[i] * 2)


0
2
4
6

Of course, instead of printing the results of this iterative arithmetic operation to the console, we could have also written the outcome to a (previously initialized) variable, and hence, made it available for future use. In fact, it is now your task to implement such a procedure in W02-1 that calculates the mean value from a sequence of numbers.

For further details, please consult the corresponding worksheet.


while loops

In contrast to for loops, that iterate over an input sequence until there are no items left in it, while loops repeat a given piece of code as long as a particular condition is True. Hence, the number of iterations depends on a conditional statement that is evaluated at the start of each repetition rather than a fixed-length input list.

while condition :
   indentedStatement to repeat


Source: https://www.tutorialspoint.com

Just like for for loops, the start and end of a while loop is clearly demarcated from the remaining code through indentation.


In [5]:
n = 0

while n < 3:
    print(n)
    n += 1


0
1
2

Brief digression

To be honest, our list of assignment operators introduced in an earlier session was not exactly comprehensive. In fact, the "+=" term used in the above while loop represents as much an assignment as "=", with the sole exception that the right side of the equation does not tell the whole truth about what is going on behind the curtain.

Here, it is important to understand that the result of an operation using a certain variable as input (e.g. "n") can easily be assigned back to the same variable by combining the arithmetic operator ("+") with an equals sign ("="). Therefore, "+=" must be regarded as a combined arithmetic–assignment operation. Of course,


In [6]:
n = 0

while n < 3:
    print(n)
    n = n + 1


0
1
2

would have generated exactly the same output, which in turn means that the coupled "+=" notation first and foremost is intended for reducing typing work. Still, it could be worth keeping in mind that "=" is not the only assignment operator out there, particularly when trying to perform arithmetic and assignment operations in one go.

Long story short, here is the list of additionally available assignment operators:

Operator Description Example Equivalent
+= Add AND a += b a = a + b
-= Subtract AND a -= b a = a - b
*= Multiply AND a *= b a = a * b
**= Exponent AND a **= b a = a ** b
/= Divide AND a /= b a = a / b
//= Floor divide AND a //= b a = a // b
%= Modulus AND a %= b a = a % b

In order to practice the knowledge we just gained about while loops (and possibly also the stuff about coupled arithmetic–assignment operations, which represent a very concise form of incrementing a counter variable), head over to the second part of W02-1 and try to solve the task we put up for you.