What's the difference?

1 variant

``````dig = int(input())
a = 1
while dig > 0:
a = a * dig % 10
dig = dig // 10
print(a)
``````
1. 2 variant
``````dig = int(input())
a = 1
while dig > 0:
a *= dig % 10
dig = dig // 10
print(a)
``````

What’s the difference? why is the code executed differently, even though the syntax is the same
dig = 415

3.12

Operating systems tested on:

Windows

`a = a * dig % 10` is `a = (a * dig) % 10`.

`a *= dig % 10` is `a = a * (dig % 10)`.

2 Likes

oh… i dont know it. thank you very much
it turns out, that last loop a*5 = 20 and 20 % 10 = 0. oh… is so interesting.
Is this not a syntaxis sugar?

The `*=` operator (and its friends `+=`, `-=`, `/=`, etc.) are called augmented assignments, which is a type of syntactic sugar, yes. You still need to be careful with operator precedence. For all augmented assignments, the precedence is:

``````# These are equivalent:
a += x
a = a + (x)

# As are these:
a *= x
a = a * (x)
``````

where `x` can be a single variable or an expression, as in your case.

2 Likes

Quibble: your equivalences aren’t quite the same in some edge cases.

``````t = [], 2, 3
t[0] = t[0] + [1]  # raises a TypeError, t[0] is unchanged
t[0] += [1]        # raises a TypeError, but t[0] becomes [1]
``````
1 Like

I understood
Thank you very much