Python provides built-in support for different types of numbers. The three most commonly used numeric types are:
- int - for whole numbers (e.g., 5, 100, -20)
- float - for decimal or floating-point numbers (e.g., 3.14, -0.5)
- complex - for complex numbers with a real and imaginary part (e.g., 3 + 4j)
Let’s explore each type with examples.
Example 1: Working with Integers (int)
x = 10
y = -4
print("Sum:", x + y)
print("Product:", x * y)Integers are whole numbers without any fractional or decimal component.
Example 2: Using Floating-point Numbers (float)
length = 5.5
width = 2.0
area = length * width
print("Area of rectangle:", area)Floats are used when precision is needed for decimals. Any number with a decimal point is treated as a float.
Example 3: Complex Numbers
a = 2 + 3j
b = 1 - 2j
result = a + b
print("Result of complex addition:", result)Python has built-in support for complex numbers, which consist of a real and an imaginary part. The imaginary part is denoted using j.
Example 4: Type Checking
num1 = 7
num2 = 3.14
num3 = 2 + 5j
print(type(num1)) # Output: <class 'int'>
print(type(num2)) # Output: <class 'float'>
print(type(num3)) # Output: <class 'complex'>You can use the type() function to check the type of any variable or value.
Example 5: Converting Between Number Types
integer_value = 10
float_value = float(integer_value)
complex_value = complex(integer_value)
print("As float:", float_value)
print("As complex:", complex_value)Python allows easy conversion between numeric types using functions like float() and complex().
Summary
intis used for whole numbersfloathandles decimal numbers and real valuescomplexsupports real and imaginary parts- You can use
type()to identify a number’s type - Conversion between number types is simple and built-in
Understanding how Python handles different numeric types is essential when performing calculations, working with user input, or building mathematical functions and programs.
