Python:Operators
From AIMSWiki
| Table of contents |
Numbers
The standard arithmetical operators on numbers are defined:
- Addition
>>> 2 + 3 5
- Subtraction
>>> 1000000000000000 - 1 999999999999999L
- Multiplication
>>> (3 + 2j) * 1j (-2+3j)
- Division
>>> 1.0 / 8.0 0.125
|
A note on division: in the current release (version 2.5) of Python from __future__ import division at the top of all your Python files to use (and get used to) the new behaviour from the start. |
- Exponentiation
>>> 400 ** 0.5 20.0
There are some unusual ones:
- Floor division (literally, dividing two numbers and taking the floor of the result)
>>> 3.5 // 0.6 5.0
- Remainder
>>> 3.5 % 0.6 0.50000000000000011
(Note the small error caused by using floating point numbers.)
Strings
Coming soon...
Lists
The following examples use the lists
x = ['a', 1, 'b', 2] y = [3, ['hello', 'there'], 10.25]
Joining and repeating lists
>>> x + y ['a', 1, 'b', 2, 3, ['hello', 'there'], 10.25] >>> x * 3 ['a', 1, 'b', 2, 'a', 1, 'b', 2, 'a', 1, 'b', 2]
Adding to a list
>>> x += [9.5, 3.25] >>> print x ['a', 1, 'b', 2, 9.5, 3.25] >>> x.append(4) # This adds a single element to the end of the list >>> print x ['a', 1, 'b', 2, 9.5, 3.25, 4]
Comparing lists
>>> x == y False >>> y == [3, ['hello', 'there'], 10.25] True
Finding and changing elements in a list
>>> 'b' in x # Check if a value is in the list True >>> 3 in x False
>>> del x[2] # This deletes the value at index 2 from the list >>> print x ['a', 1, 2, 9.5, 3.25, 4]
Logical operators
- Equal to:
== - Not equal to:
!= - Less than:
< - Less than or equal to:
<= - Greater than:
> - Greater than or equal to:
>= - Logical and:
and - Logical or:
or - Logical not:
not
Here is a pretty complex example:
(x >= 0) and (x <= 3) and not ((x > 1) and (x < 2))
If x has the value 0.5, the above evaluates to
( True ) and ( True ) and not ((False) and (True )) ( True ) and ( True ) and not (False) ( True ) and ( True ) and ( True ) True
On the other hand, if x is 1.1:
( True ) and ( True ) and not ((True ) and (True )) ( True ) and ( True ) and ( False ) False
Return to the Python index

