Skip to Content

2. Operators

An operator is, in general, a typographical symbol that means something special to the Python interpreter, and tells it to do something with the literals or variables next to it. Many are basic mathematical functions like addition and subtraction. Comparison functions are also operators, and will be listed here, but their usage will be treated in more depth in Section 4. Control flow.

Functions are similar, but tend to be user-defined, tend to be full words and the syntax is often different. Some examples should help.

2.1. Mathematical operators

You may have noticed the * symbol in this line of the preceding section:

python code
            print("Five squared is ", 5*5)
        

This is an example of an operator; it tells Python to take the two literals next to it and multiply them. Python recognizes the following operators:

+ Addition; also used for string concatenation

e.g. 1

python code
            five = 2+3
        

e.g. 2

python code
            company = "Abercrombie" + " and " + "Fitch"
        

- Subtraction; will also yield the negative of a number
e.g. 1

python code
            three = 5-2
        

e.g. 2

python code
            minusfive = -5
        

* Multiplication; can also be used for repeating strings
e.g. 1

python code
            fivesquared = 5*5
        

e.g. 2

python code
            threecheers = "Rah! "*3 # produces "Rah! Rah! Rah! "
        

** Exponentiation
The double asterisk indicates that the first number is to be taken to the power of the second:

e.g.

python code
            fivesquared = 5**2
        

/ Division

python code
            e.g. three = 6/2
        

There is a big caveat here. The result you get will actually be different here depending on which version of Python you are using. In general it's very important to use the correct data types, and you must realize that numbers with decimal points like 2.0 (floats) are a different type from numbers without a decimal point like 2 (integers).

(Note: You are probably using Python 3.x.)

In Python 3.x and above, if you divide two integers, or an integer and a float, or two floats, the result will be a float. So you always get the full value of the quotient.

python code
            quotient = 7/2 # result: 3.5 (a float, not an integer)
        

In Python 2.x and below, if you divide two integers, the result will be an integer, with any remainder rounded down. So:

python code
            quotient = 7/2 # result: 3, not 3.5
        

In general it is safest to always use floats when you want a full decimal answer.

// Truncating division

This gives the quotient sans remainder; i.e., what you would get in Python 2.x if you divide two integers.

python code
            quotient = 7//2 # result is 3 in any version of Python
        

% Modulo operator

This gives the remainder of a division:

python code
            remainder = 7%2 # result is 1, since 7/2 = 3 remainder 1
        

2.2. Comparison operators

The other major class of operators you will use in Python are comparison operators. These take two quantities, perform the comparison indicated, and return a 'True' or 'False' value which can be used in further computations.

< Less than, > Greater than

e.g. 1

python code
            2 < 5 # yields 'True'
        

e.g. 2

python code
            2 <= 2 # yields 'True'
        

== Equal to, != Not equal to

e.g. 1

python code
            3==5 # yields 'False'
"Cat" != "Dog" # yields 'True'
        

Note that it's very important to use two equal signs when testing for equality, as just one equal sign indicates assignment. In other words:

python code
            a==5 # Returns 'True' if a is equal to 5, and 'False' otherwise
a=5 # Assigns the value 5 to the variable a
        

2.3. Boolean operators

These operators, in contrast to the symbols seen thus far, are simple words, which perform Boolean logic on 'True' and 'False' data.

and - Boolean AND

python code
            a and b # Returns 'True' if both a and b are 'True' and 'False' otherwise
        

or - Boolean OR

python code
            a or b # Returns 'True' if either a or b are 'True' and 'False' otherwise
        

not - Boolean NOT

python code
            not a # Returns 'True' if a is 'False' and 'False' if a is 'True'
        

2.4. Operator precedence

There is an order of operations for operators, just like in standard algebra, and it generally follows the same rules. The top-priority operators are executed first, then the lower-priority ones. Here is the list of operators in descending order of priority:

- Negation (i.e., a negative sign in front of one number takes priority over all else)
** Exponentiation
*, /, , % Multiplication, division, floor division, modulo (all same priority; evaluated in left-to-right order)

+,- Addition, subtraction

All comparison operators (<, >, <=, =>,==, !=)

All Boolean operators (and, or, not)

So for a complex example:

python code
            -5**2 < 2 or 2+5*2==12
        

This line will:

  1. Square the number -5 (get +25) and see if it's less than 2 (returns False)
    2. Multiply 5 by 2 and add 2 (get 10+2, or 12) and see if it's the same as 12 (returns True)
    3. Check if either the left hand side or right hand side were True (the right side was), and return True if so

So the line has the value 'True'.

Parentheses can be used to order operations just like in algebra, and are recommended if only for your own sanity!

python code
            ( ((-5)**2) < 2 ) or ( (2+(5*2)) == 12 )
        

is, at the least, much easier to read.

Up to Index
Previous: 1. Basic concepts | Next: 3. Basic IO functions