Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. abs() / round() / divmod() / pow()

abs() / round() / divmod() / pow()

Since: Python 2(2000)

Built-in functions for computing absolute values, rounding, division with remainder, and exponentiation. These cover the basic arithmetic operations you commonly need in numerical calculations.

Syntax

abs(number)

# Rounds a number to the specified number of decimal places.
round(number, ndigits)

# Returns the quotient and remainder as a tuple.
divmod(dividend, divisor)

# Computes exponentiation.
pow(base, exponent)
pow(base, exponent, modulus) # base^exponent mod modulus (fast modular exponentiation)

# The ** operator also computes exponentiation.
base ** exponent

Function List

FunctionDescription
abs(number)Returns the absolute value of a number. Works with integers, floats, and complex numbers.
round(number, ndigits)Rounds a number to the specified number of decimal places. If ndigits is omitted, rounds to the nearest integer.
divmod(a, b)Returns a tuple (quotient, remainder) from dividing a by b.
pow(base, exponent)Raises base to the power of exponent. If a third argument (modulus) is provided, computes modular exponentiation efficiently.
base ** exponentThe exponentiation operator. Produces the same result as pow(base, exponent).

Sample Code

abs_round_divmod.py
print(abs(-42)) # Outputs '42'.
print(abs(-3.14)) # Outputs '3.14'.
print(abs(3+4j)) # Outputs the norm of the complex number: '5.0'.

# Round numbers with round().
print(round(3.14159, 2)) # Outputs '3.14'.
print(round(3.14159, 4)) # Outputs '3.1416'.
print(round(2.5)) # Outputs '2' (banker's rounding).
print(round(3.5)) # Outputs '4' (banker's rounding).
print(round(1234, -2)) # Outputs '1200' (rounded to the nearest hundred).

# Get the quotient and remainder at once with divmod().
quotient, remainder = divmod(17, 5)
print(quotient) # Outputs '3' (17 ÷ 5 = 3 remainder 2).
print(remainder) # Outputs '2'.

# Use divmod() to convert seconds into hours, minutes, and seconds.
total_seconds = 3661
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
print(f'{hours}h {minutes}m {seconds}s') # Outputs '1h 1m 1s'.

# Compute exponentiation with pow().
print(pow(2, 10)) # Outputs '1024'.
print(2 ** 10) # Also outputs '1024'.
print(pow(2, -1)) # Outputs '0.5'.

# Use the third argument of pow() for modular exponentiation (useful in cryptography).
print(pow(2, 10, 1000)) # Outputs '24' (2^10 mod 1000).

Running the code produces the following output:

python3 abs_round_divmod.py
42
3.14
5.0
3.14
3.1416
2
4
1200
3
2
1h 1m 1s
1024
1024
0.5
24

Common Mistakes

Common Mistake 1: round(2.5) Does Not Return 3

Python's round() uses banker's rounding (round half to even, per IEEE 754). Values exactly halfway between two integers (x.5) are rounded toward the nearest even number, so the behavior differs from conventional rounding.

# NG: assuming round(2.5) returns 3
print(round(0.5)) # 0 (banker's rounding)
print(round(1.5)) # 2 (banker's rounding)
print(round(2.5)) # 2 (banker's rounding)
print(round(3.5)) # 4 (banker's rounding)
print(round(4.5)) # 4 (banker's rounding)

When strict half-up rounding is needed, use ROUND_HALF_UP from the decimal module.

from decimal import Decimal, ROUND_HALF_UP

# OK: strict half-up rounding with decimal
def round_half_up(value, digits=0):
    d = Decimal(str(value))
    quantize_str = '1' if digits == 0 else '0.' + '0' * digits
    return float(d.quantize(Decimal(quantize_str), rounding=ROUND_HALF_UP))

print(round_half_up(0.5)) # 1.0
print(round_half_up(2.5)) # 3.0
print(round_half_up(3.5)) # 4.0

Common Mistake 2: Wrong Argument Order for divmod

The arguments to divmod(a, b) are "dividend, divisor" in that order. Reversing them changes the quotient and remainder.

total_seconds = 125

# arguments are reversed
minutes_ng, seconds_ng = divmod(60, total_seconds) # reversed!
print(minutes_ng, seconds_ng) # 0 60 (incorrect)

The corrected version is:

minutes_ok, seconds_ok = divmod(total_seconds, 60)
print(minutes_ok, seconds_ok) # 2 5 (correct)

Common Mistake 3: abs() and Floating-Point Errors

If a floating-point calculation contains rounding errors, abs() returns the value as-is. Care is needed when comparing the result.

result = 0.1 + 0.2 - 0.3
print(result) # 5.551115123125783e-17 (not exactly 0)
print(abs(result)) # 5.551115123125783e-17
print(abs(result) < 1e-10) # True (check whether it is within an acceptable tolerance)

Practical Patterns

Common patterns used in real-world code for money, distance, and time conversion.

price = 1980
tax_rate = 0.10
tax = price * tax_rate
print(f'Pre-tax: {price} yen')
print(f'Tax: {round(tax)} yen') # banker's rounding
print(f'Total: {price + round(tax)} yen')

# Find score differences using absolute value
scores = {'Yagami Light': 98, 'L Lawliet': 97, 'Amane Misa': 85, 'Yagami Soichiro': 79, 'Near': 94}
target = scores['Yagami Light']
for name, score in scores.items():
    diff = abs(score - target)
    print(f'Difference from {name}: {diff} pts')

# Convert seconds to hours, minutes, and seconds
def format_time(total_seconds):
    hours, rem = divmod(total_seconds, 3600)
    minutes, seconds = divmod(rem, 60)
    return f'{hours}h {minutes}m {seconds}s'

print(format_time(7384)) # 2h 3m 4s
print(format_time(59)) # 0h 0m 59s
abs_round_divmod_practice.py
python3 abs_round_divmod_practice.py
Pre-tax: 1980 yen
Tax: 198 yen
Total: 2178 yen
Difference from Yagami Light: 0 pts
Difference from L Lawliet: 1 pts
Difference from Amane Misa: 13 pts
Difference from Yagami Soichiro: 19 pts
Difference from Near: 4 pts
2h 3m 4s
0h 0m 59s

Details

abs() converts a negative number to its positive counterpart. It is commonly used to measure the magnitude of a difference. For complex numbers, it returns the norm (magnitude) of the vector formed by the real and imaginary parts.

round() uses Python's banker's rounding (round half to even), so values exactly halfway between two integers (x.5) are rounded toward the nearest even number. For example, round(2.5) returns 2 and round(3.5) returns 4. This differs from the conventional rounding rule (round half up). If you need standard rounding, use the decimal module.

divmod() computes both the quotient and remainder in a single call, making it convenient for unit conversions such as breaking a total number of seconds into hours, minutes, and seconds. The three-argument form pow(a, b, c) computes modular exponentiation efficiently for large numbers and is used in cryptographic algorithms such as RSA.

For mathematical functions such as square root, ceiling, and floor, see math.sqrt() / math.ceil() / math.floor().

If you find any errors or copyright issues, please .