< eelmine | Table of Contents | next > |
5.1 INTRODUCTION TO ITERATIONS
Loops and iterations allow for the execution of a block of code repeatedly. These constructs are essential for automating repetitive tasks, working through data structures, and implementing algorithms that require repeated actions until a condition is met. There are two key constructs for loops and iterations to be aware of: the while
and for
loops.
UPDATING VARIABLES
Before we dive deeper into the different types of loops, it’s important to note how variables can be updated in Python.
Updating variables means taking the previous value of the variable and altering it, so that the result is dependent on the previous value of the variable.
x = 0 x = x + 1
Here the value of x is recalculated by adding 1 to the previous value of x. The order of operations is as follows.
1. evaluate the right side 2. then assign this new value to the variable on the left.
If you attempt to update a variable that hasn't been initialized, Python will throw a NameError
as it tries to compute the right-side expression before the assignment. This means you must first declare and assign an initial value to a variable before updating it.
Python makes these operations more convenient with shorthand operators: +=
for incrementing
(increasing the value) and -=
for decrementing
(decreasing the value). Unlike some languages that use ++
and -
for incrementing and decrementing, Python requires the more verbose x += 1
or x = x + 1
.
For example, we can use a loop to sum values together and use incrementing/decrementing for updating variables in the process. Here is a brief example, but don't get too hung up on it right now, we'll cover everything about loops more in depth in the next sections of this chapter. Here's a simple example in Thonny of summing all the numbers from one through 5.
Remember that for the range()
function, the second parameter is not inclusive. This means that range(1,4)
would generate a sequence of numbers from 1 to 3, not 1 to 4.
KEY THINGS TO REMEMBER
- Variables must be initialized before they are used in an update operation within loops to avoid errors.
- Common operations in loops include incrementing or decrementing a variable’s value, usually by one, to modify the variable gradually.
- Python uses
+=
for incrementing and-=
for decrementing.
SELF-CONTROL EXERCISES
< eelmine | Table of Contents | next > |