Quick Overview
`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.
Write a function tri_area(base, height) that takes the base and height of a triangle and returns its calculated area.
Implementing mathematical formulas in code is a key skill in graphics, game physics, and data science algorithms.
The geometric formula for the area of a triangle is (base * height) / 2:
def tri_area(base, height):
return (base * height) / 2
# Testing our function
print(tri_area(3, 2)) # Output: 3.0
print(tri_area(7, 4)) # Output: 14.0
print(tri_area(10, 10)) # Output: 50.0
/ performs float division in Python 3, returning a decimal number (e.g. 3.0).// performs floor division, discarding decimals to return a whole integer.base * height / 2 works because multiplication and division share equal precedence from left to right. However, using parentheses (base * height) / 2 makes your code clearer.0, the calculated area is 0.0.Use / for float division. Next, let's find the next integer in sequence!
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.
Python integers have no fixed width, so `n + 1` never overflows the way a 32-bit `int` would. The value simply grows to whatever memory allows.