Editor settings

General settings

Save settings

Learn to program with Python

Increase the value of a variable #

You can increase the value of a variable by performing some type of calculation on the variable, then reassign it back to the same variable.

For example, you can increase a value of a variable by 1 like so:

x = 10
x = x + 1
print(x) # output: 11

In the example above, the variable x is created with the value 10. The value is then incremented by 1 with the code x + 1 and then reassigned back to the variable x.

However, you can also increase the value of a variable by using what's called compound assignment operator, which is a shorthand way of performing some action on the variable and reassigning it back to the original variable.

We can increase the value of a variable with the operator += like so:

x = 10
x += 1 # equivalent to x = x + 1
print(x) # output: 11

Exercise #

  • Rewrite the code on line 3 to use += to increase the value of x by 1
  • Value of x should be 21
Output will be displayed here