In Python there are three types of numbers:
- Integer: Integer (or int) number type indicates a whole number.
- Float: If the number has a decimal portion, it is a floating-point number (or float).
- Complex: Complex numbers have real and imaginary parts.
x = 5 # Integer
y = 3.14 # Float
z = 2 + 3j # Complex Number
Number Type Conversion
To convert from one number type to another, you can use int()
, float()
, or complex()
functions.
x = 5
y = 3.14
z = 2 + 3j
t = float(x) # converting from int(x) to float (t = 5.0)
w = int(y) # converting from float(y) to int (w = 3)
u = complex(x) # converting from int(x) to complex
Arithmetic Operators
You can use the following arithmetic operators in numbers:
Operator | Description | Format | Example |
---|---|---|---|
+ | Addition | a + b | 3 + 5 = 8 |
– | Subtraction | a – b | 10 – 7 = 3 |
* | Multiplication | a * b | 3 * 4 = 12 |
/ | Division | a / b | 21 / 7 = 3 |
% | Modulus | a % b | 23 % 7 = 2 |
** | Exponent | a ** b | 2 ** 4 = 16 |
// | Floor Division – Rounds down to nearest whole number | a // b | 9 // 2 = 4 -9 // 2 = -5 |
str() Function
To concatenate a number with a string in Python, first you need to convert number to string using str()
function, otherwise Python will give TypeError
.
TypeError: can only concatenate str (not “int”) to str
age = 32
print("Hello, I'm " + age + " years old.")
str()
function converts number to string
print("Hello, I'm " + str(age) + " years old.")
# Hello, I'm 32 years old.