Mathematical operator precedence
In Python, the mathematical operator precedence is determined by the PEMDAS rule, which stands for Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction. Here’s how it works in Python:
- Parentheses
()– This has the highest precedence and will always be evaluated first. - Exponents
**– After parentheses, exponentiation is performed next. - Multiplication
*, Division/, Floor Division//, and Modulus%– These operators have the same level of precedence. They are evaluated from left to right. - Addition
+and Subtraction-– These also have the same level of precedence and are evaluated last, from left to right.
It’s important to note that in Python, operators with the same precedence level (like multiplication and division) are evaluated based on their position in the expression, from left to right. This is slightly different from how some might interpret PEMDAS, where multiplication could be incorrectly assumed to always come before division.
Floats vs Decimals in Python
Do you think float and decimal is same, it seems be but not actually same in python. Here’s the example:
x = 2
y = x / 33
z = y * 33
print(x, y, z)
print(type(y))
print(type(z))
if x==z:
print("sun")
else:
print("moon")
what is the output of above program?
Well, it’s “sun” as X and Z both are converted to floating numbers
x = 20
y = x / 77
z = y * 77
print(x, y, z)
print(type(y))
print(type(z))
if x==z:
print("sun")
else:
print("moon")
what’s the output of above program?
if you say “sun” then it’s wrong 🙂
citation : 15. Floating Point Arithmetic: Issues and Limitations — Python 3.12.3 documentation
| Float | Decimal |
| A float in Python is a floating-point number that is represented in binary format. It’s an approximate number data type. | The decimal module provides the Decimal data type, which is a fixed-precision decimal number. |
| Floating-point numbers are represented using the IEEE 754 standard, which means they can have rounding errors and not all decimal numbers can be represented exactly. | Unlike floats, Decimal numbers can represent certain decimal fractions exactly and are not subject to binary floating-point rounding errors. |
| Floats are typically used when you need to perform a lot of calculations at a high speed since they are supported by the hardware of most modern computers. | Decimals are slower than floats because they are implemented in software, but they are useful when exact decimal representation is needed, such as in financial applications where precision is crucial. |
In summary, use float for general-purpose floating-point arithmetic and when performance is a concern, and use Decimal when you need high precision and exact decimal representation, especially for monetary calculations. Remember that Decimal is part of the decimal module, so you need to import it before you can use it:

