Operators

Python's has many operators, like +, -, /, *, ** and %. They are polymorphic and work differently for the different data types.

Some operation using numbers


>>> (1+2)**2
9
>>> (2+3*4)/2
7
>>> 7%3   # % is the modulo operator
1
>>> 7 == 7
True
>>>

Some operators using strings


>>> "Andrew" + " " + "Dalke"
'Andrew Dalke'
>>> "*" * 10
'**********'
>>> "My name is %s.  What's your name?"  % "Andrew"
'My name is Andrew.  What's your name'
>>> "My first name is %s and family name is %s" % ("Andrew", "Dalke")
'My first name is Andrew and family name is Dalke'
>>> "My first name is %(first)s.  Is yours also %(first)s?" % \
...    {"first": "Andrew", "family": "Dalke"}
'My first name is Andrew.  Is yours also Andrew?'
>>> "Andrew" == "Dalke"
False
>>> 

Some operators using lists


>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> [1, 2] * 3
[1, 2, 1, 2, 1, 2]
>>>

Operator Precedence

When you have an expression that contains several operators, they are evaluated in an order determined by their precedence. The precedence of the operators follows the rules of arithmetic. Others follow a precedence that usually does what you think they should do. If uncertain you can use parentheses to force precedence:

2+3*4;    # evaluates to 14, multiplication has precedence over addition
(2+3)*4;  # evaluates to 20, parentheses force the precedence

Logical Operators

The boolean operators are and and or. These use the truth value of their two parameters figure out if the result is true or false. (Actually, they return the value which made the expression true or false, but I won't get into that now.)

>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False or True
True
>>> 

This page based on Operators


Andrew Dalke
Last modified: Tue Feb 3 12:25:09 SAST 2004