Python Basics
Python Numbers
Python supports three built-in numeric types — int, float and complex — and gives you simple operators to perform math on them.
Number Types in Python
An int is a whole number with no decimal point, a float is a number with a decimal point, and a complex number has a real and imaginary part, written with a j suffix. Complex numbers are rarely needed outside scientific computing.
whole = 10 # int
decimal = 10.5 # float
imaginary = 2 + 3j # complex
print(type(whole), type(decimal), type(imaginary))Arithmetic Operations
Python supports all standard math operations, plus a couple of handy extras like floor division and exponents.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 2 | 7 |
| - | Subtraction | 5 - 2 | 3 |
| * | Multiplication | 5 * 2 | 10 |
| / | Division | 5 / 2 | 2.5 |
| // | Floor Division | 5 // 2 | 2 |
| % | Modulus (remainder) | 5 % 2 | 1 |
| ** | Exponent (power) | 5 ** 2 | 25 |
a = 7
b = 2
print(a + b, a - b, a * b, a / b, a // b, a % b, a ** b)Converting Between Number Types
Use int() to convert a value to a whole number, and float() to convert it to a decimal number. This is common when working with user input, since input() always returns text.
text_number = "42"
as_int = int(text_number)
as_float = float(text_number)
print(as_int, as_float)Rounding Numbers
The built-in round() function rounds a float to the nearest whole number, or to a given number of decimal places if you pass a second argument.
price = 19.6789
print(round(price)) # 20
print(round(price, 2)) # 19.68Use / for normal division that keeps decimals, and // when you specifically need a whole-number result, like splitting items evenly.
