In any form of programming, one inevitably needs to add, subtract, combine, split, and otherwise manipulate data. To do this, small symbols and reserved words are used to tell the computer exactly what needs to be done. In this brief tutorial, we will look at the operators and how to use the most common of them.
Python uses the following operators:
+ addition (unary plus)
- subtraction (unary minus)
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
<> an obsolete form of 'not equal to'
For strings, however, Python has just one operator: + for concatenation. All other operations are performed using modules like string or re.
Numerical operations (aka, 'Arithmetic')
As you might imagine, you can perform any mathematical operation you like on a numeric literal.
d = 300 pi = 3.14159265 circumference = pi * d r = d/2 c = 2 * pi * r
As discussed under strings, one concatenates a string instead of adding it. One can concatenate strings or their values. The result is a string that shows no indication that the two parts were ever separate. So if you need a space between the parts, you must be sure to include it when the two strings are joined.
a = 'big' b = 'baboons' phrase = a + b full_phrase = b + " with " + a + " bahoochies" print phrase print full_phrase
output: bigbaboons baboons with big bahoochies
One can also test a string for equality or inequality relative to another string:
if computer == "laptop"
if brand != "generic"
For more information on operators, see the Python Reference Manual.