Skip to content

Python Number Types

Number types are used to store numeric values. They are immutable data types, which means changing the value of a numeric variable actually creates a new object.

Python supports three main numeric types:

  1. Integer (int): Positive or negative integers without decimal points. Integers in Python 3 can be arbitrarily large, limited only by memory.
  2. Float (float): Positive or negative real numbers with decimal points. Can also be represented in scientific notation (e.g., 2.5e2 represents 2.5 * 10^2 = 250).
  3. Complex (complex): Composed of a real part and an imaginary part, in the form a + bj, where j is the imaginary unit.
python
# Integers
x = 10
y = -3000
z = 12345678901234567890

# Floats
pi = 3.14
price = -19.99
scientific = 1.23E4  # 1.23 * 10^4 = 12300.0

# Complex numbers
c = 1 + 2j

Basic Arithmetic Operations

Python supports all standard arithmetic operators.

OperatorNameExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division5 / 22.5
//Floor Division5 // 22
%Modulo5 % 21
**Exponentiation5 ** 225

Example:

python
a = 10
b = 3

print(f"a + b = {a + b}")
print(f"a / b = {a / b}")
print(f"a // b = {a // b}")
print(f"a % b = {a % b}")
print(f"a ** b = {a ** b}")

Type Conversion in Operations

When an expression contains both integers and floats, Python automatically converts integers to floats to maintain precision. This conversion is implicit.

python
result = 3 + 4.5
print(result)       # Output: 7.5
print(type(result)) # Output: <class 'float'>

Number Type Conversion Functions

You can also use built-in functions to explicitly convert between different number types.

  • int(x): Converts x to an integer (truncates the decimal).
  • float(x): Converts x to a float.
  • complex(x): Converts x to a complex number with real part x and imaginary part 0.
  • complex(x, y): Creates a complex number with real part x and imaginary part y.
python
print(int(9.9))         # Output: 9
print(float(10))        # Output: 10.0
print(complex(5))       # Output: (5+0j)
print(complex(2, -3))   # Output: (2-3j)

Math Module math

For more advanced mathematical operations like trigonometric functions, logarithms, square roots, etc., you need to import the math module.

python
import math

# Pi
print(math.pi) # Output: 3.141592653589793

# Square root
print(math.sqrt(16)) # Output: 4.0

# Round up
print(math.ceil(4.2)) # Output: 5

# Round down
print(math.floor(4.8)) # Output: 4

# Sine function
print(math.sin(math.pi / 2)) # Output: 1.0

Content is for learning and research only.