agyanadda@gmail.com

Python Numbers and Type Casting

Python Basics 1 min read Updated Dec 4, 2026 Topic 6 of 32

Number types

  • int — whole numbers of any size: 7, -3, 10_000_000 (underscores for readability)
  • float — decimals: 3.14, 1.5e3
  • complex — 2 + 3j (rarely needed)

Type conversion (casting)

  • int("25") → 25, int(9.8) → 9 (cuts the decimal)
  • float("3.5") → 3.5
  • str(100) → "100"
  • int("abc") raises a ValueError

Useful built-ins

abs(-5), round(3.14159, 2), pow(2, 10), max(), min(), sum(), divmod(17, 5) → (3, 2)

The math module

import math → math.sqrt, math.ceil, math.floor, math.pi, math.factorial

Random numbers

import random → random.randint(1, 6), random.choice(list), random.shuffle(list). Use the secrets module for passwords and OTPs.

Float precision

0.1 + 0.2 gives 0.30000000000000004. For money, use the decimal module or store amounts in paise as integers.

Example

Example — Number practice Python
import math, random
from decimal import Decimal

price = "499"
qty = 3
total = int(price) * qty
print("Total:", total)

print(17 / 5, 17 // 5, 17 % 5, 2 ** 10)
print(round(3.14159, 2), math.sqrt(144), math.ceil(4.1))

print(0.1 + 0.2)
print(Decimal("0.1") + Decimal("0.2"))

print("Dice:", random.randint(1, 6))
print("Population:", f"{1_400_000_000:,}")

Output: Total: 1497, 3.4 3 2 1024, 3.14 12.0 5, 0.30000000000000004, 0.3, a random dice number, Population: 1,400,000,000

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does int(9.9) return?

Exercise 2 True / False

0.1 + 0.2 equals exactly 0.3 with Python floats.

Exercise 3 Fill in the Blank

Get the square root with math.___(144)

Frequently Asked Questions

Use the decimal module with quantize, for example Decimal('2.675').quantize(Decimal('0.01'), rounding=ROUND_HALF_UP), or keep amounts as integers in the smallest unit (paise).