0

This is a basic understanding problem.

I tried reordering some code, and though the operations are supposedly equivalent I get different values. I started with this line:

q, r, m = 10*q, 10*(r-m*t), (10*(3*q+r))//t - 10*m

and changed it to:

q*=10;  r=10*(r-m*t);   m= (10*(3*q+r))//t - 10*m;

(With initial values being q= 1, r= 6, t= 3, m= 3).

When I run only the second line, m gets value -30 (which is accurate if I followed the order-of-operations correctly), while running the first yields m= 0, which is what the program calls for.

What am I missing here? Does the comma method assign the value after all other assignments are done?

3
  • 3
    When using x, y = foo, bar syntax, all statements are executed before assigning the values to the variables. When using x=foo; y=bar, they are not. Commented Mar 15, 2019 at 21:32
  • So it was that simple.. I guess it is better in every way for the code 😅 Commented Mar 15, 2019 at 21:36
  • Note that you can safely extract the q assignment. See my answer for details Commented Mar 15, 2019 at 21:40

3 Answers 3

1

The assignments in q, r, m = 10*q, 10*(r-m*t), (10*(3*q+r))//t - 10*m are done independently by evaluating the right hand side of all the assignments without anyone affecting the others, meaning that when (10*(3*q+r))//t - 10*m is evaluated, the old value of q is used, not the new 10*q (same with r). Notice that the only difference is in the value of m, which depends on the values of r and q, which aren't changing while m is being assigned.

Sign up to request clarification or add additional context in comments.

Comments

0

The issue is that your first snippet of code evaluates each expression on the right before assigning the results to your q, r, and m variables. Your second snippet instead assigns:

q*=10
r=10*(r-m*t)

-before evaluating:

m= (10*(3*q+r))//t - 10*m

which changes the result. If you must use the latter snippet, you'll need to introduce a temporary variable to store the original q and r variable values for usage in the final expression.

In fact, since q does not depend on either of the other variables, you could in fact assign its value last, keeping the other two in tract, to slightly simplify the expression:

r, m = 10*(r-m*t), (10*(3*q+r))//t - 10*m
q *= 10

Comments

0

In the first case, all the assignments use the values of the variables before any assignments are done.

In the second case, you're changing some variables before others (your later assignments are using the new values of the variables).

Compare a, b = b, a with a = b; b = a. This first will swap the values, the second will not.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.