Lesson 4: Python Number Methods

Python provides many built-in functions to perform mathematical operations efficiently. In this lesson, you'll learn about important number methods like round(), pow(), abs(), and divmod(). These functions help with rounding, exponentiation, finding absolute values, and dividing numbers with ease.

Topics Covered
  • Rounding Numbers with round()
  • Raising Numbers to a Power using pow()
  • Getting the Absolute Value using abs()
  • Finding Quotient and Remainder using divmod()

4.1 The round() Function

The round() function rounds a floating-point number to the nearest whole number or to a specified number of decimal places.
Syntax:
round(number, digits)
- number: The number to be rounded.
- digits: Optional. Specifies the number of decimal places.


# Example: Rounding to two decimal places
x = 23.55648
n = round(x, 2)
print(n)
# Output: 23.56

4.2 The pow() Function

The pow() function raises a number to a specified power.
Syntax:
pow(base, exponent)
It performs the same operation as the ** operator.


# Example: Power calculation
x = pow(4, 2)  # Same as 4 ** 2
a = pow(3, 3)  # Same as 3 ** 3

print(x)  # Output: 16
print(a)  # Output: 27

4.3 The abs() Function

The abs() function returns the absolute (non-negative) value of a number. This is useful when you only need the magnitude of a number, regardless of its sign.


# Example: Absolute value
y = abs(-27)
b = abs(5)

print(y)  # Output: 27
print(b)  # Output: 5

4.4 The divmod() Function

The divmod() function takes two numbers and returns a tuple containing their quotient and remainder.
Syntax:
divmod(x, y)(quotient, remainder)


# Example: Using divmod()
result = divmod(7, 3)
print(result)
# Output: (2, 1)
# 2 is the quotient and 1 is the remainder.

These methods make mathematical operations cleaner and easier to implement in real-world applications.


Quick Exercise

1. Which function returns a non-negative number in Python?




2. How do you round a figure to two decimal places in Python?

figure = 24.5678