Lessons
Python Basics
Python Variables
Operators in Python
Conditional Statements in Python
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Loops in Python
Python Arrays and Functions
Conclusion
Python Numeric Types
Python Numbers
In Python, numbers are used for mathematical operations, and there are three main numeric types:
- int: Integer, a whole number.
- float: Floating-point number, a decimal number.
- 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
1x = 1 # int
2y = 2.8 # float
3z = 1j # complex
To verify the type of any object in Python, use the type()
function:
python
1print(type(x)) # Output: <class 'int'>
2print(type(y)) # Output: <class 'float'>
3print(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
1x = 1
2y = 35656222554887711
3z = -3255522
4
5print(type(x)) # Output: <class 'int'>
6print(type(y)) # Output: <class 'int'>
7print(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
1x = 1.10
2y = 1.0
3z = -35.59
4
5print(type(x)) # Output: <class 'float'>
6print(type(y)) # Output: <class 'float'>
7print(type(z)) # Output: <class 'float'>
Floats can also represent scientific numbers, using an "e" or "E" to indicate the power of 10:
Example:
python
1x = 35e3
2y = 12E4
3z = -87.7e100
4
5print(type(x)) # Output: <class 'float'>
6print(type(y)) # Output: <class 'float'>
7print(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
1x = 3 + 5j
2y = 5j
3z = -5j
4
5print(type(x)) # Output: <class 'complex'>
6print(type(y)) # Output: <class 'complex'>
7print(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
1x = 1 # int
2y = 2.8 # float
3z = 1j # complex
4
5# Convert from int to float
6a = float(x)
7
8# Convert from float to int
9b = int(y)
10
11# Convert from int to complex
12c = complex(x)
13
14print(a) # Output: 1.0
15print(b) # Output: 2
16print(c) # Output: (1+0j)
17
18print(type(a)) # Output: <class 'float'>
19print(type(b)) # Output: <class 'int'>
20print(type(c)) # Output: <class 'complex'>