Wednesday, February 24, 2021

Python shell as a simple calculator

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:

  1. + Addition
  2. - Subtraction
  3. * Multiplication
  4. / Floating-point division
  5. // Integer division
  6. % Modulus (remainder)
  7. ** 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

Share:

0 comments:

Post a Comment