Calculate with whole numbers and decimals using +, -, *, /, //, % and **, follow operator precedence and update variables with augmented assignment.
About 35 minBeginner5 exercisesFree
You will be able to
Tell integers from floats and predict which one an operation produces
Use floor division // and remainder % to split quantities into whole units and leftovers
Raise numbers to a power with ** and control the order of operations with parentheses
Update a variable in place with +=, -=, *= and /=
A warehouse has 53 jars of honey and packs them 12 to a box. How many full boxes does it ship, and how many jars are left on the shelf? A payroll clerk needs gross pay to the halala. A savings app needs to know what 1000 SAR becomes after three years at 5% interest. All of these are arithmetic, and Python has an operator for each step.
Python has two main kinds of number:
an integer (int) is a whole number with no decimal point: 53, 0, -12;
a float is a number with a decimal point: 12.5, 0.15, 3.0. The name comes from "floating-point", the way computers store decimals.
3 and 3.0 are equal in value but are different types. You can ask Python which type a value has with type().
Try it: Change jars to 53.0. Which lines of output change?
The arithmetic operators
Operator
Meaning
Example
Result
+
addition
7 + 2
9
-
subtraction
7 - 2
5
*
multiplication
7 * 2
14
/
division
7 / 2
3.5
//
floor division (whole part)
7 // 2
3
%
remainder (modulo)
7 % 2
1
**
power
7 ** 2
49
Two rules about the result's type:
/always gives a float, even when the division is exact: 6 / 2 is 3.0.
For the other operators, two integers give an integer; if either side is a float, the result is a float: 2 * 1.5 is 3.0.
Floor division and remainder belong together. // tells you how many whole times one number fits into another; % tells you what is left over. That answers the honey question directly.
Try it: Change per_box to 10, then to 53. What do // and % give when the division is exact?
Operator precedence
When an expression has several operators, Python follows a fixed order, the same as in maths:
** (power) first;
then *, /, //, % (left to right);
then + and - (left to right).
Parentheses override the order: whatever is inside them is worked out first. So 2 + 3 * 4 is 14, but (2 + 3) * 4 is 20. When in doubt, add parentheses — they cost nothing and make your intention clear to the reader.
One surprise with negative numbers: // rounds down (towards minus infinity), not towards zero, and % follows the same rule so that the check (a // b) * b + a % b == a always holds.
principal =1000
rate =5# percent per year
years =3
balance = principal *(1+ rate /100)** years
print(balance)print(round(balance,2))
Try it: Remove the parentheses around 1 + rate / 100 and run it. Work out why the result is so different.
round(balance, 2) rounds to two decimal places; you'll look at rounding properly in the next lesson.
Augmented assignment
Updating a variable from its own value is so common that Python has a shorter form. These pairs do exactly the same thing:
Long form
Short form
total = total + price
total += price
stock = stock - 3
stock -= 3
amount = amount * 0.9
amount *= 0.9
share = share / 4
share /= 4
There are also //=, %= and **=. The variable must already exist: total += 5 on a name that was never assigned raises NameError.
A shopping cart built up with augmented assignment
total =0
total +=45.5# olive oil
total +=12# bread
total +=30.25# cheeseprint("Subtotal:", total)
total *=0.9# 10% member discountprint("After discount:", total)
Try it: Add a line that takes off a 5 SAR coupon with -= and print the final total.
Guided practice · ●difficulty 1 of 5 · about 4 min
Convert minutes to hours and minutes
A call centre logs how long each call lasted in minutes. Write a program that reads a whole number of minutes (call input() with no message — the tests type the value for you) and converts it to hours and minutes.
Store the whole hours in hours and the remaining minutes in leftover, then print them like this. For 135:
2 h 15 min
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Challenge · ●●●difficulty 3 of 5 · about 8 min
Plan a shipment of boxes
A honey farm packs jars into boxes. The program reads the number of jars, then how many jars fit in one box (two whole numbers; the tests type them for you).
Calculate:
full_boxes — how many boxes can be filled completely,
loose_jars — how many jars are left over,
boxes_needed — how many boxes are needed to ship every jar (a partly filled box still counts as a box).
Print them. For 53 jars and 12 per box:
Full boxes: 4
Loose jars: 5
Boxes needed: 5
Use only arithmetic operators — no if statements. Think about what boxes_needed should be when the jars fit exactly.
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Challenge · ●●difficulty 2 of 5 · about 6 min
Grow a savings balance
A savings account pays a fixed yearly interest rate, and the interest is added to the balance every year (compound interest). After years years the balance is:
principal × (1 + rate ÷ 100) to the power of years
The program reads the principal (a decimal), the yearly rate in percent (a decimal) and the number of years (a whole number) — the tests type them for you. Store the result in balance and print it rounded to 2 decimal places with round(balance, 2). For 1000, 5, 3:
Balance: 1157.63
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Debugging · ●●difficulty 2 of 5 · about 4 min
Fix the average score
A teacher's program reads three test scores (whole numbers; the tests type them for you) and prints their average. For the scores 70, 80 and 90 it should print:
Average: 80.0
but it prints Average: 180.0. Find and fix the bug. The average must keep its decimal part (for 70, 85 and 90 it is 81.666...).
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Edge cases · ●●difficulty 2 of 5 · about 6 min
Build a cart total step by step
A grocery app builds the cart total one step at a time. The program reads three item prices (decimals) and then a coupon value (a decimal) — the tests type them for you, one per line.
Using augmented assignment (+=, *=, -=) on a variable called total:
start total at 0 and add each of the three prices;
apply a 10% member discount (multiply by 0.9);
subtract the coupon.
Print the subtotal (before the discount) and the final total. For 20, 30, 50 and a coupon of 5:
Subtotal: 100.0
Total: 85.0
Your program must also work when an item is free (price 0) or there is no coupon (0).
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Summary
Integers are whole numbers; floats have a decimal point. Mixing them, or using /, gives a float.
// gives the whole number of times one number fits into another and % gives the remainder.
** raises to a power and is worked out first; then *, /, //, %; then + and -. Parentheses override the order.
Augmented assignment (+=, -=, *=, /=) updates a variable from its own current value.