When you work with Loops, you’ll find life is a bit easier if you know some of these tips.
Simplifying Math
The book calls this first tip Augmented Operators, other languages refer to it as shortcut math. Either way, the end result is the same. Quite often you will be working with a variable and you need to modify its value. Well, you could say something like:
variable = variable + 1
However, it is easier to work to write it in a short cut manner.
variable += 1
As you can see, when you add a value to a variable, you can put the plus sign in front of the equals. That tells Python to add it to the existing value. You are not limited to 1, or even a set value. You can modify the value of a variable by another variable.
# x = 5
# y = 3
x += y
# x now equals 8
Of course, you are not limited to just addition. This basic concept works for almost all of Python’s mathematical operators we looked previously.
Operator | Example | Equal To |
+= | x += 7 | x = x + 7 |
-= | x -= 3 | x = x – 3 |
*= | x *= 2 | x = x * 2 |
/= | x /= 2 | x = x / 2 |
%= | x %= 5 | x = x % 5 |
Common examples of this is when you are calculating a running total or items being purchased, or subtracting a value from a balance.
Incrementors (adding 1 to an existing value) and decrementors (subtracting 1 from an existing value) are also common, especially if you are using a conditional loop as a counting loop.
Input Validation Loops
Using an if statement is good for making sure that you’ve been given valid data. However, using a loop makes sure that the user doesn’t enter bad data a second time.
Here’s an example where we test for a negative volume for a container. Clearly, a container cannot have a negative space.
volume = 0
while volume <= 0 :
volume = float(input('Please enter the volume of the container. This should be a positive number:'))
Notice how it will just keep checking and asking for a positive value until it gets it. This is sometimes known as a validation loop. An advantage to this is it is easier to catch and fix an error at this point, than it is once everything has been entered, and then figure out how to go back and fix it.
Additional Tips when Working with Loops in Python was originally found on Access 2 Learn