Arithmetic Operators

Arithmetic operators work with the numeric types Float,Int, and LongTable 3-1 describes them, including three we have yea to encomhpr: modulus (%), which gives the remainder; exponential (**), which raises one number to the power of another number; and abs, which gives a number's absolute value.

One example of moduius is 3 /2, which give s the remainder of 1 (3/2 = 1!/t). Ano^ger is 10/7, which gives a remainder of 3 (10/7 = p 3/h), In Python, we express the previous sentence as

Once you understand modulus, the divmod () function, which we'll discuss in a later chhptf r, should come easily to you.

Table 3-1. Arithmetic Operators

Operator

Description

Interactive Session

+

Addition

>>> x = 1 + 2 >>> print (x) 3

Subtraction

>>> x = 2 - 1 >>> print (x) 1

*

Multiplication

>>> x = 2 * 2 >>> print (x) 4

/

Integer division returns an Integer type; float division returns a float type

Integer division:

Float division:

>>> x = 10.0 / 3.3333 >>> print (x) 3.000030000300003

o, o

Modulus—gives the remainder; typically used for integers

>>> x = 10 % 3 >>> print (x) 1

* *

Exponential

>>>

x = 10**2

>>>

print(x)

100

divmod

Does both of the division operators at once and returns a

This:

tuple; the second item in the tuple contains the remainder.

divmod (x,y is eq uiva 1 ent to x/y, x%y

>>>

divmod (10,3)

(3,

1)

Is the

same as this:

>>>

10/3,10%3

(3,

1)

This:

>>>

divmod (5,2)

(2,

1)

I s the

same as thi s:

t>>>

5/2, 5%2

(2,

1)

abs

Finds the absolute value of a number

>>>

abs(100)

100t

>>>

abs(-100)

100

-,+

Sign

t>>>

1, -1, +1, +-1

(1,

-1, 1, -1)

Was this article helpful?

0 0

Post a comment