Reassignment

Reassignment

Assigning to an existing variable replaces its value:

count = 1
count = 5
print(count)

Output:

5

The old value is gone. count holds 5.

The right side of = is evaluated first, so a variable can be reassigned using its own current value:

count = 5
count = count + 1
print(count)

Output:

6

count + 1 is computed first, producing 6. Then 6 is assigned to count.

Exercise

The starter code creates score with the value 0. Below that line:

  1. Reassign score to 10.
  2. Increase score by 5, using score itself on the right side of the =.
  3. Print score. The output should be 15.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestReassignment(unittest.TestCase):
    def test_score_ends_at_15(self):
        self.assertEqual(score, 15)
score = 0

score = 10
score = score + 5
print(score)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.