1. Computing

Beginning Python: Operators

From , former About.com Guide

1. Introduction

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.

Other tutorials in this series: 1 | 2 | 3 | 4 | 5 | 6

2. Common Operators

Python uses the following operators:

+ addition (unary plus)
- subtraction (unary minus)
* multiplication
**
/ division
% modulo
< 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.

3. Using Operators

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 
 

String operations

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.

Other tutorials in this series: 1 | 2 | 3 | 4 | 5 | 6

©2013 About.com. All rights reserved.