Python Numeric Types

Python Numbers

In Python, numbers are used for mathematical operations, and there are three main numeric types:

  1. int: Integer, a whole number.
  2. float: Floating-point number, a decimal number.
  3. complex: Complex numbers with real and imaginary parts.

Python Numeric Types

You create numeric variables by assigning values to them. Here's an example:

python
1
2
3
x = 1      # int
y = 2.8    # float
z = 1j     # complex

To verify the type of any object in Python, use the type() function:

python
1
2
3
print(type(x))  # Output: <class 'int'>
print(type(y))  # Output: <class 'float'>
print(type(z))  # Output: <class 'complex'>

Python Integer

An integer is a whole number, positive or negative, without decimals. Python allows integers of unlimited length.

Example:

python
1
2
3
4
5
6
7
x = 1
y = 35656222554887711
z = -3255522

print(type(x))  # Output: <class 'int'>
print(type(y))  # Output: <class 'int'>
print(type(z))  # Output: <class 'int'>

Python Float

A float is a number that has a decimal point or an exponential (scientific notation) representation. Floats can be positive or negative.

Example:

python
1
2
3
4
5
6
7
x = 1.10
y = 1.0
z = -35.59

print(type(x))  # Output: <class 'float'>
print(type(y))  # Output: <class 'float'>
print(type(z))  # Output: <class 'float'>

Floats can also represent scientific numbers, using an "e" or "E" to indicate the power of 10:

Example:

python
1
2
3
4
5
6
7
x = 35e3
y = 12E4
z = -87.7e100

print(type(x))  # Output: <class 'float'>
print(type(y))  # Output: <class 'float'>
print(type(z))  # Output: <class 'float'>

Complex Numbers

Complex numbers are written with a "j" to represent the imaginary part. A complex number consists of a real part and an imaginary part.

Example:

python
1
2
3
4
5
6
7
x = 3 + 5j
y = 5j
z = -5j

print(type(x))  # Output: <class 'complex'>
print(type(y))  # Output: <class 'complex'>
print(type(z))  # Output: <class 'complex'>

Type Conversion

Python provides built-in functions to convert numbers from one type to another:

  • int(): Convert a number to an integer.
  • float(): Convert a number to a float.
  • complex(): Convert a number to a complex.

Example:

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
x = 1      # int
y = 2.8    # float
z = 1j     # complex

# Convert from int to float
a = float(x)

# Convert from float to int
b = int(y)

# Convert from int to complex
c = complex(x)

print(a)  # Output: 1.0
print(b)  # Output: 2
print(c)  # Output: (1+0j)

print(type(a))  # Output: <class 'float'>
print(type(b))  # Output: <class 'int'>
print(type(c))  # Output: <class 'complex'>

Frequently Asked Questions