1.4: Arithmetic operators

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    1.4: Arithmetic operators

    After “Hello, World”, the next step is arithmetic. Python provides operators, which are special symbols that represent computations like addition and multiplication.

    The operators +, -, and * perform addition, subtraction, and multiplication, as in the following examples:

    >>> 40 + 2
    42
    >>> 43 - 1
    42
    >>> 6 * 7
    42
    

    The operator / performs division:

    >>> 84 / 2
    42.0
    

    You might wonder why the result is 42.0 instead of 42. I’ll explain in the next section.

    Finally, the operator ** performs exponentiation; that is, it raises a number to a power:

    >>> 6**2 + 6
    42
    

    In some other languages, ^ is used for exponentiation, but in Python it is a bitwise operator called XOR. If you are not familiar with bitwise operators, the result will surprise you:

    >>> 6 ^ 2
    4
    

    I won’t cover bitwise operators in this book, but you can read about them at http://wiki.python.org/moin/BitwiseOperators.


    This page titled 1.4: Arithmetic operators was last modified on Tue, 01 Dec 2020 03:31:13 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.