Python beginner: I don't understand the calculated result of a code snippet

a = 6
b = 3
a /= 2 * b
print( a )

I am following the Python Essentials 1 course offered by the Cisco Networking Academy. The answer given to the above code snippet is 1.0, but I cannot get this result. I calculate it to be 9.0.

What am I not understanding?
1 Like

When you say ‘you calculate it to be’ do you mean that you are getting 9.0 as the result when you run that code, or that you are doing an independent calculation (not using Python)?

The answer 1.0 is certainly correct, for what it’s worth.

Thanks Kevin.

I am manually trying to calculate it using what I understand to be the process to see if I get the same result as running it in Python, which I’m not :stuck_out_tongue_closed_eyes:

I am not understanding the /= shortcut operator. When I look at:

a /= 2 * b

I am thinking:

a = a / 2 * b

:bulb: My (mis)understanding as I have just worked it out is that the priority should be * followed by /. I was following the left-to-right priority order. :roll_eyes:

Yes, that is a misunderstanding, and it’s not an operator priority (precedence) issue.

You should think of /= as a function call, and not an operator, because it really is a function call. Given that, the right-hand side is an argument to be passed to the function, and since it is an expression that expression must be evaluated before it can be passed to the function.

The result is that a /= 2 * b is effectively the same as a /= (2 * b).

1 Like

So easy once you know how! :grinning:

Thank you, Kevin.

Right, this misses the order of operations. When people say that a /= b is “equivalent to” a = a / b, what they mean is that the b is the entire right-hand side of the /=. The reason we have the ability to use operators like /= is to make the code easier to understand, not harder. This way, we can easily express: “we need to divide the existing value of a by something; now here’s what we’ll divide it by (2 * b)”.

1 Like

This is all great advice. Thank you.