Changing a Variable's Value
A program runs one command after another, from top to bottom. That's why a variable can have different values at different moments. To change the value of a variable, store a new one in it with =:
writer = "Edgar Allan Poe"
print("The best writer is", writer)
writer = "William Shakespeare"
print("The best writer is", writer)This prints:
The best writer is Edgar Allan Poe
The best writer is William ShakespeareWhen the first print() runs, writer holds "Edgar Allan Poe". The next line replaces this value with "William Shakespeare", and the old value is gone. So the second print() prints the new value.
The new value can be calculated from the current one:
score = 10
score = score + 5
print(score)This prints:
15In math, score = score + 5 would make no sense. In Python, though, it means “score gets score + 5”: Python first calculates the right side with the current value (10 + 5), and then stores the result, 15, in score.
Programs do this so often that Python has a shortcut for it: score += 5 means the same as score = score + 5. Subtracting works the same way: score -= 5 means score = score - 5. For example, money in a wallet:
wallet = 100
wallet -= 30 # you bought a book
wallet += 50 # you sold an old game
print(wallet)This prints:
120Write += and -= without a space between the two characters.
Instructions
- 1
The player has lost a life. Below the existing code, change the value of
livesto2and print it again in the same way. The program should print:Lives: 3 Lives: 2 - 2
Then the player finds an extra life. Below, add one to
liveswith+=. - 3
Print
livesonce more in the same way. The last line of the output should beLives: 3.