Python fundamentals
Arithmetic operators
Calculate with +, -, *, /, //, %, and **, and understand order of operations.
Lesson 9 of 63
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Beginner
On this page5 sections
Python can calculate with numbers. The common arithmetic operators are + for addition, - for subtraction, * for multiplication, and / for division. Division with / produces a float, even when the result is a whole number.
print(8 + 2)
print(8 - 2)
print(8 * 2)
print(8 / 2)10 6 16 4.0
Whole-number division and remainder
For nonnegative numbers and a positive divisor, // finds how many whole groups fit, and % finds the remainder. This is useful when converting a total number of minutes into hours and remaining minutes.
total_minutes = 135
hours = total_minutes // 60
remaining_minutes = total_minutes % 60
print(hours)
print(remaining_minutes)2 15
Powers and grouping
The ** operator raises a number to a power. Powers are evaluated before multiplication and division, which are evaluated before addition and subtraction. Parentheses make the intended order explicit.
print(2 ** 3)
print(2 + 3 * 4)
print((2 + 3) * 4)8 14 20
Why this works
Use / when you want a division result that may contain a fraction. For nonnegative totals and a positive unit size, // gives complete units and % gives what remains. For example, 135 minutes is 135 // 60 complete hours and 135 % 60 remaining minutes.
Practice
Set sessions to 3 and minutes_per_session to 25. Calculate total_minutes with multiplication, then print the whole hours and remaining minutes using // and %.
What are 75 // 60 and 75 % 60?
Reveal answer
They are 1 and 15, representing one hour and 15 remaining minutes.
Try another case
Convert 130 minutes into whole hours and remaining minutes.
Check your answer
Reveal answer
130 // 60 is 2 hours; 130 % 60 is 10 minutes.
Your progress
Reveal the check answer or reach the end to complete this lesson.