Python Numbers · Exercises
Beginner

Python Numbers Exercises

4 exercises that build on the Python Numbers lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: Python has three built-in number types, int for whole numbers, float for decimal numbers and complex for numbers with an imaginary part, and each follows its own rules for size, division and precision. By the end you can tell int, float and complex apart, write readable number literals, use //, %, ** and divmod, round and format results, and avoid the 0.1 + 0.2 float trap. You will practise: Minutes to hours and minutes; Predict the division results; Fix the price check; Split a bill in whole cents.

0 / 4 completed

Python Numbers practice exercises

1. Minutes to hours and minutes

Write code Easy

Write a function to_hours_minutes(total_minutes) that returns a tuple (hours, minutes). For example to_hours_minutes(135) returns (2, 15). Use // and % or divmod().

Your code
def to_hours_minutes(total_minutes):
    # return (hours, minutes)
    pass

print(to_hours_minutes(135))

2. Predict the division results

Predict the output Easy

Division and rounding have a few surprises. Type exactly what the program prints.

Read this code
print(7 // 2, 7 % 2)
print(-7 // 2, -7 % 2)
print(type(6 / 3))
print(round(2.5), round(3.5))

3. Fix the price check

Fix the bug Medium

total_matches(prices, expected) should be True when the prices add up to the expected total, but float errors make it fail for [0.1, 0.7] and 0.8. Fix the function with math.isclose().

Your code
import math

def total_matches(prices, expected):
    return sum(prices) == expected

print(total_matches([0.1, 0.7], 0.8))

4. Split a bill in whole cents

Write code Hard

Write split_bill(total_cents, people) that returns a list of people integers adding up to exactly total_cents. The shares may differ by at most one cent, with the larger shares first. Example: split_bill(1001, 3) returns [334, 334, 333]. Use divmod() and a loop, no floats.

Your code
def split_bill(total_cents, people):
    shares = []
    # base share and leftover cents: divmod(total_cents, people)
    return shares

print(split_bill(1001, 3))

Next lessonPython Casting

More Python Numbers examples · All Python exercises