Quick Overview
Unit conversion is one multiply per step: hours * 3600 + minutes * 60. Converting each unit separately and adding avoids the rounding drift that chained divisions introduce.
Write a function how_many_seconds(hours, minutes) that converts hours and minutes into total seconds.
Combining multiple input variables into a single unified metric is a standard step in data preprocessing pipelines.
Multiply hours by 3600 (60 minutes * 60 seconds) and minutes by 60, then add them together:
def how_many_seconds(hours, minutes):
return (hours * 3600) + (minutes * 60)
# Testing our function
print(how_many_seconds(2, 0)) # Output: 7200
print(how_many_seconds(1, 12)) # Output: 4320
print(how_many_seconds(0, 30)) # Output: 1800
(hours * 3600) + (minutes * 60).Combine formulas using parenthesized expressions. Next, let's check if a number is less than or equal to zero!
A function with no return hands back None, so a forgotten one surfaces as a TypeError at the call site rather than at the line that actually caused it.
minutes * 60 returns an int when given an int, while / always produces a float regardless of the operands. Multiplication preserves the type; division does not.
base * height / 2 always yields a float in Python 3 because / never returns an int, even for whole numbers. // floors instead, which is almost never what an area wants.