SwadhyAI Notes

All Python notes

Python Numbers 🔢

Numeric Types

Python supports three distinct numeric types: integers, floating point numbers, and complex numbers. Variables of numeric types are created when you assign a value to them.

✨ Int (Integer)

Int is a whole number, positive or negative, without decimals, of unlimited length (limited only by your computer's memory).

python
x = 1
y = 35656222554887711
z = -3255522

print(type(x))  # <class 'int'>

💡 Pro Tip: Underscores for Readability

You can use underscores to make large numbers more readable. Python ignores them.

python
population = 7_000_000_000
print(population)  # Output: 7000000000

✨ Float (Floating Point)

Float is a number, positive or negative, containing one or more decimals.

python
x = 1.10
y = 1.0
z = -35.59
scientific = 35e3  # 35000.0

⚠️ Watch Out: Floating Point Precision

Floats are approximations. Be careful when comparing them directly.

python
print(0.1 + 0.2)
# Output: 0.30000000000000004 (Not exactly 0.3!)

✨ Complex Numbers

Complex numbers are written with a "j" as the imaginary part.

python
x = 3 + 5j
y = 5j
z = -5j

print(x.real)  # 3.0
print(x.imag)  # 5.0

♾️ Infinity and NaN

Floats can also represent Infinity and "Not a Number" (NaN).

python
positive_infinity = float('inf')
negative_infinity = float('-inf')
not_a_number = float('nan')

🎯 Real-World Application: Money

Never use floats for money because of precision errors (like the 0.30000000000000004 issue).
In real banking apps, developers use the decimal module or store money as integers (cents) to ensure perfect accuracy.