Python mostly uses a similar syntax to other computer languages for performing
numerical arithmetic:
x + y # addition
x – y # subtraction
x * y # multiplication
x / y # division
x // y # floored division
x % y # remainder of x / y
x ** y # x to power y
pow(x, y) # x to power y
The variables x and y can be integers, floating point numbers or a mixture. If both are
integers the result is also an integer, except in the case of division for Python version 3.
Otherwise the result is a floating point number, even if it represents a whole number. Thus
4.6 + 2.4 is 7.0, not 7. This also includes the floored quotient, x//y, which gives the whole
number part of the division of x and y as floating point. For example, 13.3//2.1 gives 6.0,
not the integer equivalent.
5
A non-programmer might wonder why x//y is useful at all. However, it turns out that it
does come up in various contexts, but mostly when x and y are integers. This brings up an
oddity, which Python, before version 3, shares in common with many computer languages,
namely that for integers, the operation x/y is the same as x//y. A non-programmer might
expect that 13/5 is equal to 2.6, but in fact it is equal to 2, the integer part of that. This is in
contrast to doing division where at least one floating point number is involved like 13/5.0,
13.0/5 or 13.0/5.0, which are all indeed equal to 2.6. Hence in Python 2, if you have two
integers and want to do the traditional non-integer division then you can explicitly convert
one of them to a floating point number using the float() function, so, for example,
float(13)/5. (There is also an int() function for converting floating point numbers to their
integer part.)
It is a historic accident that integer division behaves this way, although the situation
changes in Python 3, where integer division reverts to its more traditional ‘human’
meaning, so 13/5 now does equal 2.6. Accordingly, it is recommended that in Python 2
you avoid x/y if x and y are integers, but instead use x//y.
Example arithmetic results:
13 + 5 # 18
13.0 + 5 # 18.0
13 – 5 # 8
13 – 5.0 # 8.0
13 / 5 # 2 in Python 2; 2.6 in Python 3
float(13) / 5 # 2.6
13.0 / 5 # 2.6
13 // 5 # 2
13 // 5.0 # 2.0
As in most computer languages, multiplication and division have higher precedence
than addition and subtraction, but arithmetic expressions can be grouped using parentheses
to override the default precedence. So we have:
13 * 2 + 5 # 31 since "*" has higher precedence than "+"
(13 * 2) + 5 # 31
13 * (2 + 5) # 91
A common situation that arises is that a variable needs to be incremented by some
value. For example, you could have:
x = x + 1
which increases the value of x by 1. Python allows a shorthand notation for this kind of
statement:
x += 1
Also, it allows similar notation for the other arithmetic operations, for example:
x *= y
assigns x to be the product of x and y, or in other words x is redefined by being multiplied
by y.
Do'stlaringiz bilan baham: