Execute Program

Python for Programmers: Augmented and Chained Assignment

Welcome to the Augmented and Chained Assignment lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Expressions like x = x + 1 are common, so Python has a dedicated "augmented assignment" operator. name += value does the same thing as name = name + value.

  • >
    x = 3
    x += 5
    x
    Result:
    8Pass Icon
  • There are also equivalents for other mathematical operators: *=, -=, and /=. However, Python doesn't have the x++ operator, which adds 1 to x in many other languages. Trying to use it raises a SyntaxError exception.

  • (You can type error when a code example will cause an error.)

  • >
    x = 3
    x++
    x
    Result:
    SyntaxError: invalid syntax (<string>, line 2)Pass Icon
  • We can also assign the same value to multiple variables in one line. This convenient feature is called "chained assignment."

  • >
    x = y = 3
    x += 1
    y += 2
    x + y
    Result:
    9Pass Icon