With the three basic number types described in the previous post, it is possible to use the Python shell as a simple calculator using the following operators:
- + Addition
- - Subtraction
- * Multiplication
- / Floating-point division
- // Integer division
- % Modulus (remainder)
- ** Exponentiation
These are binary operators in that they act on two numbers (the operands) to produce a third (e.g. 2**3 evaluates to 8).
Python 3 has two types of division: floating-point division (/) always returns a floating-point (or complex) number result, even if it acts on integers. Integer division (//) always rounds down the result to the nearest smaller integer (“floor division”); the type of the resulting number is an int only if both of its operands are ints; otherwise it returns a float. Some examples should make this clearer:
Regular (“true”) floating-point division with (/):
>>> 2.7 / 2
1.35
>>> 9 / 2
4.5
>>> 8 / 4
2.0
The last operation returns a float even though both operands are ints.
Integer division with (//):
>>> 8 // 4
2
>>> 9 // 2
4
>>> 2.7 // 2
1.0
Note that // can perform integer arithmetic (rounding down) on floating-point numbers. The modulus operator gives the remainder of an integer division:
>>> 9 % 2
1
>>> 4.5 % 3
1.5
Again, the number returned is an int only if both of the operands are ints.
We will discuss about operator precedence in the next post
0 comments:
Post a Comment