Python provides built-in functions to perform common mathematical operations easily without writing manual code.
Overview
Python has several built-in functions to work with numbers. You can perform calculations, rounding, powers, and aggregate computations.
1) Common Mathematical Functions
# Absolute value
print(abs(-7)) # 7
# Round a number to n decimal places
print(round(3.14159, 2)) # 3.14
# Power
print(pow(2, 5)) # 32 (same as 2 ** 5)
# Quotient and remainder
print(divmod(17, 5)) # (3, 2)
# Minimum and maximum
nums = [5, 3, 9, 1]
print(min(nums)) # 1
print(max(nums)) # 9
# Sum of numbers
print(sum(nums)) # 18
2) More Examples
# Using abs with float
print(abs(-3.14)) # 3.14
# Combining functions
x, y = 7, 3
quotient, remainder = divmod(x, y)
print("Quotient:", quotient, "Remainder:", remainder)
# Using sum with generator
print(sum(i*i for i in range(5))) # 0^2+1^2+2^2+3^2+4^2 = 30
Common Mistakes
- Using
abs()with non-numeric types →TypeError - Passing wrong arguments to
round()(e.g., negative decimal places incorrectly) - Using
sum()with non-iterable →TypeError - Using
pow()with string arguments →TypeError - Forgetting that
divmod()returns a tuple (quotient, remainder)
💡 Try It Yourself
- Find the absolute value of -123.45
- Round 7.6789 to 1 decimal place
- Compute 3 to the power 4 using
pow() - Use
divmod()to find quotient and remainder of 29 divided by 6 - Given a list of numbers, find the sum, minimum, and maximum
No comments:
Post a Comment