O GoConqr está de visual novo! Conte para nós o que você achou.

Módulo 8 de 11 · Texto

Shortcut operators

David Khieu

Shortcut operators

It's time for the next set of operators that make a developer's life easier.

Very often, we want to use one and the same variable both to the right and the left sides of the = operator.

For example, if we need to calculate a series of successive values of powers of 2, we may use a piece like this:

x = x * 2

You may use an expression like this if you can't fall asleep and you're trying to deal with it using some good, old-fashioned methods:

sheep = sheep + 1

Python offers you a shortened way of writing operations like these, which can be coded as follows: 

x *= 2

sheep += 1

Let's try to present a general description for these operations. 

If op is a two-argument operator (this is a very important condition) and the operator is used in the following context:

variable = variable op expression

it can be simplified and shown as follows:

variable op= expression

Take a look at the examples below. Make sure you understand them all. 

i = i + 2 * j ⇒ i += 2 * j

var = var / 2 ⇒ var /= 2

rem = rem % 10 ⇒ rem %= 10

j = j - (i + var + rem) ⇒ j -= (i + var + rem)

x = x ** 2 ⇒ x **= 2

Instruções

Para avançar no curso, envie uma tentativa deste quiz. Você pode enviá-la depois da última pergunta.

Ir para o módulo escolhido

Fale Conosco

Sobre o que é sua mensagem?

O que você acha do novo visual?

Você gostou?