Integers (int)
Integers are whole numbers β positive, negative, or zero. Python integers have unlimited precision: they can be arbitrarily large with no overflow.
x = 10
y = -5
z = 0
big = 10 ** 100 # Python handles huge numbers!
print(type(x)) #
print(big) # 1 followed by 100 zeros
Floats (float)
Floats are decimal numbers. They use 64-bit IEEE 754 double-precision, which means they have ~15-17 significant digits but can have precision issues.
pi = 3.14159
temp = -23.5
scientific = 1.5e-3 # 0.0015
print(type(pi)) #
print(0.1 + 0.2) # Floating point gotcha!
print(round(0.1 + 0.2, 2)) # Fix: use round()
Never use floats for financial calculations. Use the decimal module instead: from decimal import Decimal
Arithmetic Operations
Python supports all standard arithmetic operations. Note: ** is power, // is floor division, % is modulo (remainder).
a, b = 17, 5
print(a + b) # 22 - addition
print(a - b) # 12 - subtraction
print(a * b) # 85 - multiplication
print(a / b) # 3.4 - true division (always float)
print(a // b) # 3 - floor division (rounds down)
print(a % b) # 2 - modulo (remainder)
print(a ** b) # 1419857 - power (17^5)
The math Module
Python's built-in math module provides advanced mathematical functions.
import math
print(math.sqrt(16)) # 4.0 - square root
print(math.pi) # 3.141592653589793
print(math.ceil(4.2)) # 5 - round up
print(math.floor(4.8)) # 4 - round down
print(math.log(100, 10))# 2.0 - log base 10
print(math.factorial(5))# 120
print(math.gcd(48, 18)) # 6 - greatest common divisor
Number Type Conversion
Convert between number types with int(), float(), and complex(). Note that int() truncates (does not round) floats.
print(int(3.9)) # 3 - truncates, does NOT round
print(float(5)) # 5.0
print(int("42")) # 42 - from string
print(float("3.14"))# 3.14
# Check if string is numeric before converting
value = "123"
if value.isdigit():
print(int(value) * 2) # 246