Can the += operator be used to add more than one value at a time?

Just out of curiosity, say we want to subtract some value from a variable. Is there any shorthand for that as well? Like “-=” or something like that?

Indeed there is.

a = 40
b = 84
c = 24
d = 100

a += 2
b -= a
c *= b
d /= c

There are others of these assignment operators which we can find listed under that title in the Python docs.

2 Likes

Thank you Sir, this solves the doubt…

1 Like

You’re welcome. FYI, I’ve changed the link target to a less geeky page.

1 Like

how about like this:
total_price += (value1 + value2) i did this and it worked. trying to figure out its limitations, which I’m guessing it would have.

You’ll find that it works the same without grouping (brackets) since the operation on the right (addition) takes place first.

total_price = 0

new_sneakers = 50.00

total_price += new_sneakers

nice_sweater = 39.00

fun_books = 20.00

Update total_price here:

total_price+=(nice_sweater+fun_books)

print(“The total price is”, total_price)

It’s correct?

Is the total price equal to 109.00? If so the computation is correct. What the SCT expects is another thing. Does all your text match the instructions?

Is correct, the total price is 109.00.
I confirm, All your text corresponds to the instructions.
I have successfully finished the chapter: Hello world
Good evening.

1 Like

I have a question, sorry if this is a kind of dumb one but can you use like a minus sign for the +=? like -= or any other math operator?

Yes. All the basic operators can be used in augmented assignments.

For a complete list of assignment operators, see this page…

Expressions and operators - JavaScript | MDN

what’s the difference between += & =+

One is valid and the other not, in respective order. The operation is always before the assignment.

1 Like

Both of them works if
i=10
i+= 2 + 2
print( i )
output comes i=14
but when put =+ output is i=4 .
i know i=+ is i = (1) . But i cant understand why the output is 4

Because the operation does not take place, only the assignment. i becomes 2 + 2. The plus sign after the equals is like a negative sign, only positive.

Accept it as moot that =+ is NOT an augmentation assignment, but a replacement assignment.

2 Likes