Python provides shorthand operators that combine arithmetic with assignment:
| Operator | Equivalent to | Example |
|---|---|---|
+= | x = x + value | x += 5 |
-= | x = x - value | x -= 3 |
*= | x = x * value | x *= 2 |
/= | x = x / value | x /= 4 |
//= | x = x // value | x //= 3 |
%= | x = x % value | x %= 2 |
**= | x = x ** value | x **= 3 |
score = 10
score += 5 # score is now 15
score -= 3 # score is now 12
score *= 2 # score is now 24
print(score) # prints 24
When using variables, it is good practice to initialise them at the beginning of your program. This clearly identifies what variables will be used and their starting values:
# Initialise variables
total = 0
count = 0
name = ""
price = 0.0
# Use them later in the program
total += 10
count += 1
name = "Alice"
price = 9.99
Initialising variables helps you: