How do you multiply in Python?
Short answer: use the * operator. 7 * 3 returns 21. To square a number or raise it to a power, use **: 5 ** 2 returns 25. To multiply all the numbers of a list, use math.prod().
print(7 * 3) # 21
print(5 ** 2) # 25
import math
print(math.prod([1, 2, 3, 4, 5])) # 120* multiplies, ** raises to a power, math.prod() multiplies a whole list and a list comprehension multiplies each element.
Every way to multiply in Python
| What you want | Code | Result |
|---|---|---|
| Multiply two numbers | 7 * 3 | 21 |
| Square a number | 5 ** 2 or pow(5, 2) | 25 |
| Raise to any power | 2 ** 10 | 1024 |
| Multiply all the numbers in a list | math.prod([1, 2, 3, 4, 5]) | 120 |
| Multiply each element of a list | [n * 3 for n in nums] | [3, 6, 9] |
| Multiply NumPy arrays element by element | np.array([1, 2, 3]) * 3 | [3 6 9] |
| Multiply matrices | a @ b | Matrix product |
| Repeat a string | "ab" * 3 | "ababab" |
Multiply numbers with the * operator
price = 19
quantity = 3
total = price * quantity
print(total) # 57The type of the result depends on the numbers you multiply:
| Operation | Result | Type |
|---|---|---|
7 * 3 | 21 | int |
2.5 * 4 | 10.0 | float |
2 * 1.5 | 3.0 | float |
Two integers give an integer. As soon as one of them is a float, the result is a float. Floats can show tiny rounding errors, such as 0.1 * 3 returning 0.30000000000000004. Use round(0.1 * 3, 2) to show 0.3, or the decimal module when you work with money.
To multiply and update a variable at the same time, use *=:
score = 10
score *= 2
print(score) # 20