Python 9b – Number Handling

Round and format numbers cleanly (currency, fixed decimals) and extract digits for validation tasks.

Rounding numbers

Use round(value, places) to round a number to a set number of decimal places:

value = 12.6789
rounded_value = round(value, 2)
print("Rounded value:", rounded_value)  # 12.68

Fixed-decimal formatting (currency)

For always showing a fixed number of decimals (e.g. money), format with an f-string:

num_items = int(input("How many items would you like to purchase? "))
price_per_item = 4.99
total_cost = num_items * price_per_item
print(f"Your total is: £{total_cost:.2f}")
Tips:
  • Use :.2f for 2 decimal places, :.3f for 3, etc.
  • For thousands separators: {value:,.2f}1,234.57.

Practice Task 1: Precise Division

Ask for two large numbers, divide, and show the result to 3 decimal places.

Show answer
num1 = float(input("Enter a large number: "))
num2 = float(input("Enter another large number: "))
result = num1 / num2
print(f"Result: {result:.3f}")

Using numbers as strings (digit access)

Convert a number to string to access individual digits by index, then convert back with int() if needed.

Practice Task 2: Digit Extraction & Addition

Input a 10-digit number, take the 2nd and 8th digits, convert to integers, and print their sum.

Show answer
number_str = input("Enter a 10-digit number: ").strip()
digit2 = int(number_str[1])   # 2nd digit (index 1)
digit8 = int(number_str[7])   # 8th digit (index 7)
print("The sum of the 2nd and 8th digits is:", digit2 + digit8)