Mixed Operations

Evaluating a long line

A line with five operators is five small steps. Find the operator Python applies first, replace it and its operands with the value, and write the shorter line underneath. Repeat until one value is left.
Step orderOperatorsWithin the row
1( )innermost first
2**right to left
3- (negation)applied after the power next to it
4* / // %left to right
5+ -left to right
Three rules decide most of these lines.
Floor division rounds down, toward negative infinity. -8 / 5 is -1.6, so -8 // 5 is -2, not -1.
One float makes the result a float. If either operand is a float, +, -, *, // and % all give a float, and / always does. Once a float appears in a line, every step after it that touches it is a float too.
The power binds tighter than the minus sign in front of it. -2 ** 3 is -(2 ** 3).
When you write out the steps, copy every operator you have not used yet onto the next line. If a step drops one, every line after it is wrong too.
The program below prints the value of a long line and then the value of each shorter line of its steps. Every line should print the same value. Run it, then change it and run it again:
• In the Step 2 line, delete % 6, and compare that line with the line above it.
• In the Start line, change -2 ** 6 to (-2) ** 6.
• In the Step 4 line, change 12.5 to 12.
print("Start:", -2 ** 6 // 9 + 23 % 6 * 2.5)
print("Step 1:", -64 // 9 + 23 % 6 * 2.5)
print("Step 2:", -8 + 23 % 6 * 2.5)
print("Step 3:", -8 + 5 * 2.5)
print("Step 4:", -8 + 12.5)
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.