Summary: in this tutorial, you’ll learn about Python numbers and how to use them in programs.
Python supports integers, floats, and complex numbers. This tutorial discusses only integers and floats.
Integers #
The integers are numbers such as -1, 0, 1, 2, and 3, .. and they have type int.
You can use Math operators like +, -, *, and / to form expressions that include integers. For example:
x = 20
y = 10
total = x + y
print(total)
difference = x - y
print(difference)
product = x * y
print(product)
quotient = x / y
print(quotient)Output:
30
10
200
2.0To calculate exponents, you use two multiplication symbols (**). For example:
x = 3
y = 3
power = x ** y
print(power)Output:
27To modify the order of operations, you use the parentheses (). For example:
result = 20 / (10 + 10)
print(result)Output:
1.0Floats #
Any number with a decimal point is a floating-point number. The term float means that the decimal point can appear at any position in a number.
In general, you can use floats like integers. For example:
x = 0.5
y = 0.25
total = x + y
print(total)
difference = x - y
print(difference)
product = x * y
print(product)
quotient = x / y
print(quotient)Output:
0.75
0.25
0.125
2.0The division of two integers always returns a float:
x = 20
y = 10
quotient = x / y
print(quotient)Output:
2.0If you mix an integer and a float in any arithmetic operation, the result is a float:
x = 1
y = 2.0
total = x + y
print(total)Output:
3.0Due to the internal representation of floats, Python will try to represent the result as precisely as possible. However, you may get the result that you would not expect. For example:
x = 0.1
y = 0.2
total = x + y
print(total)Output:
0.30000000000000004Just keep this in mind when you perform calculations with floats. And you’ll learn how to handle situations like this in later tutorials.
Underscores in numbers #
When a number is large, it’ll become difficult to read. For example:
count = 10000000000To make the long numbers more readable, you can group digits using underscores, like this:
count = 10_000_000_000When storing these values, Python just ignores the underscores. It does so when displaying the numbers with underscores on the screen:
count = 10_000_000_000
print(count)Output:
10000000000The underscores also work for both integers and floats.
Note that the underscores in numbers have been available since Python 3.6
Summary #
- Python supports common numeric types including integers, floats, and complex numbers.
- Use the underscores to group numbers for the large numbers.
Quiz #
Python Numbers
Thank you for your feedback!