Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write a function percent(part, total) that gives part / total * 100. It must raise a ValueError with a clear message when total is 0, or when part is more than total. Then call it with (3, 4), (5, 0) and (9, 4) inside a try, and show the message for each bad call.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Check the two rules at the start of the function, and raise with a message that says what was wrong.
Check. percent(3, 4) gives 75.0. percent(5, 0) is refused with the first message. percent(9, 4) is refused with the second, which names both numbers.
Answer: The function above. The output is 75.0, Refused: the total must not be zero, and Refused: the part (9) is more than the total (4).
Log in to join the discussion.
Loading…