Home Python Page 2 - Python Operators

# The Prestigious Mathematical Operators - Python

In the previous two articles on Python, I promised to tell you about Operators, but I lied. Instead I covered such things as conditionals, sets, lists, dictionaries, and so forth. Now, at last, I am going to cover the various operators that Python has to offer, and force you, I mean teach you, to manipulate data with them.

By: James Payne
Rating:  / 8
January 14, 2008

SEARCH DEV SHED

TOOLS YOU CAN USE

Most of the mathematical operators you should be familiar with, at least if you graduated the third or fourth grade, which judging by that confused look on your face, perhaps you haven't. That's okay. I'll use little words.

In the example below we will use each of math operators to demonstrate how they function:

#!/usr/local/bin/python

print "Here is an example of using addition: 2+2 =", 2+2

print "Here is an example of subtraction: 4-2 =", 4-2

print "Here is an example of multiplication: 2*4 =", 2*4

print "Here is an example of division: 8/4 =", 8/4

print "Here is an example of truncated division: 5//3 =", 5//3

print "Here is an example of using powers: 2**9 =", 2**9

print "Here is an example of using modulos: 5%3 =", 5%3

The result of this code is:

Here is an example of using addition: 2+2 = 4

Here is an example of subtraction: 4-2 = 2

Here is an example of multiplication: 2*4 = 8

Here is an example of division: 8/4 = 2

Here is an example of truncated division: 5//3 = 1

Here is an example of using powers: 2**9 = 512

Here is an example of using modulos: 5%3 = 2

A few things to note: presently, division works the same as truncated division, though this will change in the future. Truncated division means that if you divide two integers, and the result is say, 1.25, then the program will round down to 1.

Regarding Modulos, it is used to return the remainder of a division. In the above example we divide five by three, which is 1 with a remainder of 2. So thus, and thusly, modulos would return 2.

 >>> More Python Articles          >>> More By James Payne