Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The for loop
The while loop
9. A convenient shortcut
Nested loops
break and continue
Summary

Instruction

Good! In the previous example, we incremented the value of counter in the following way:

counter = counter + 1

... which is actually a bit verbose. Luckily, we can make it shorter:

counter += 1

The expression counter += 1 says: add 1 to the variable counter. It's the exact same as counter = counter + 1, but is much shorter and quicker to write. A similar syntax works for other operations:

  • counter = counter - 5 is the same as counter -= 5
  • counter = counter * 2 is the same as counter *= 2
  • counter = counter / 4 is the same as counter /= 4

These operators are actually very popular in Python (and other programming languages), so we encourage you to use them whenever you can.

Exercise

Write a program that will print all powers of 2, beginning with 2^1 = 2 and ending with 1024.

Start by printing:

Here are some powers of 2!
Then, write each consecutive power of 2 on a new line. At the end, print:

That's enough!

Stuck? Here's a hint!

Create a variable that will hold the current value. Inside a while loop, print the value, and then use:

current_value *= 2

This will calculate the next power of the number 2.

Remember to escape the apostrophe in the final sentence using \.