Python:Basics:Numbers and operators

From Python

Jump to: navigation, search
« Contents
Numbers and operators
»
Strings Decision structures

Behind the scenes, computers are all about numbers. The CPU is endlessly ADDing, ANDing, ORing and SHIFTing bits in order to make that JPEG of Aunt Alice appear as wallpaper on your desktop.

Although human beings love numbers, we are not good at calculating them, once the figure gets beyond the number of fingers on our hands. A computer language abstracts all of these mathematical operations into higher level operations so we can use mathematics more easily.

Contents

Expressions

In programming, an expression is any combination of operators and operands. Operands are values, and operators are symbols that operate on operands. When we line up operands and operators on a line in order to make Python do something, we make an assignment statement. When Python looks at the right side of the assignment statement and performs the indicated operands on its operands, we say that it evaluates the right hand side as it returns a new value to the left hand side.

An expression can be a single operand, a combination of operands and operators, or a combination of operands and operators with an assignment statement. The following statements are all expressions.

2

2 + 2

print len("a string")

result = 2 + 3

result = 2 > 3

display("Aunt_Alice.jpg")

Python Numbers

Python has only a few number data types. The following table shows a list of them:

Type Value
int -231 thru +231 -1 (-2,147,483,6478 thru +2,147,483,647)
long int Less than or greater than an int
float Floating point number
complex numbers Two floating point numbers, one real and one imaginary.

We’ll skip the complex numbers, except to note that they display Python’s potential for heavy-duty mathematics.

Many mathematical functions are built-ins, meaning that you can use them without an import statement. For more complex operations such as trigonometry, Python provides the math module.

Python Operators

The following sections list Python’s arithmetic, comparison, and logical operators.

Arithmetic Operators

Python has the standard set of mathematical operators and one special one for integer division. The following table shows a list of them:

Operator Description
+ addition
- subtraction
*
multiplication
/ division
// integer division
% remainder

The integer division operator is for returning an integer result when dividing a floating point number.

Arithmetic Operators Examples
Line Code Meaning
1 total = 9 total is assigned the value of 9.
2 total += 10 total is assigned the value of itself plus 10.

This is the "shortcut" operator for addition. It is easier to type than "total = total + 10".

total now has the value of 19.
3 total -= 10 total is assigned the value of itself minus 10.

This is the shortcut operator for subtraction.

total now has the value of 9.
4 total *= 3 total is assigned the value of itself multiplied by 3.

This is the shortcut operator for multiplication.

total now has the value of 27.
5 total /= 2 total is assigned the value of itself divided by 2.

This is the shortcut operator for division.

total now has the value of 13, not 13.5, because / returns the integer portion of the division.
6
total = 27
 
7 from __future__ import division
 
8 total /= 2 total is assigned the value of itself divided by 2, preceded by an import from the __future__ module.

What this line says is that in a future release of Python (Python 3000, to be exact), division will include the fractional portion of the result.

total is now 13.5
9 total = ’9’ total is assigned the value of the character ’9’.

This ’9’ is not an integer, but a string data type. Even though it looks the same as the integer 9, the program cannot use it for arithmetic calculations.
10 total += 10 total, with a string value of ’9’ is assigned the value of itself plus the integer 10.

This causes a compiler error, because you cannot add a string and a number
11 total = int(total) total is converted to an integer.

This only works if the string can convert to an integer.

total now has the value of the integer 9.
12 total += .5 total is assigned the value of itself plus a floating point number.

The datatype of total now becomes float in order to accommodate the floating point total now has the value of 9.5
13 total -= .5 total is assigned the value of itself minus a floating point number.

The datatype of total is still a float, even though its decimal fraction is 0. total now has a value of 9.0
14 total = int(total) total is converted to an integer.

total now has the value of 9.
Comparison Operators

Comparison operators return Boolean values, that is, True or False. The term Boolean is a reference to George Boole, an English mathematician who invented Boolean arithmetic. You can also explicitly assign a Boolean value to a variable, and use it in a test.

The following table shows a list of comparison operators.

Operator Description
< less than
<= less than or equal

==

equal
> greater than
>= greater than or equal
!= not equal
<> not equal
Comparison Operators Examples
Line Code Meaning
1 isTrue = 9 > 8
Assigning the result of a comparison to a variable.
2 print isTrue  
  True Output.
3 print 8 >=8
 
  True Output.
4 print 8 > 8  
  False Output.
5 print 8 == 8
 
  True Output
6 print 8 == ’8’
 
  False
Output.
7 print 9 != 8
 
  True
Output.
8 print 9 <> 8  
  True
Output.
The <> operator is considered obscelescent. the != operator is preferred because it is consistent with C language notation.
Logical Operators

The logical operators and and or also return a Boolean value when used in a decision structure. However, when used outside of a decision structure, they return a value, depending on the evaluation of the expression.

You can use this behavior to create a Pythonic ternary. In programming, a ternary is an if-else statement with the test and return value all done on one ling.

Not negates the result of an expression.

Operator Description
and logical AND
or logical OR
^ exclusive OR
not logical NOT
Logical Operators Examples
Line Code Meaning
1 true1 = True Setting some Boolean variables.
2 true2 = True  
3 false1 = False  
4 false2 = False  
5 print true1 and true2  
  True Output.
6 print true1 and false1  
  False Output.
7 print true1 or true2  
  True Output.
8 print true1 or false1  
  True Output.
9 print true1 ^ true2  
  False Output.
10 print true1 ^ false1  
  True Output.
11 print false1 and false2  
  False Output.
12 print false1 or false2  
  False Output.
13 print false1 ^ false2  
  False Output.
Bit Operators

Bit operators are for operations down at the bit level.

Operator Description
~ bitwise complement
<< bitwise left shift
>> bitwise right shift
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
Bit Operators Examples
Line Code Meaning
1 print ~1
1 in binary is 0001. Taking the complement of this produces
1110. The left most bit makes it a negative number, and counting backward from 1000 makes this number -2. Add 1 to make it -1, the twos complement of 1.
  -2
Output.
2 print 4 << 1 4 in binary is 0100. Shifting each bit to the left produces 1000, or decimal 8.
  8 Output.
3 print 4 >> 1 Shifting each bit to the right produces 0010, or decimal 2
  2 Output.
4 print 4 | 8 ORs these numbers, with result given:
0100 (decimal 4)
1000 (decimal 8)
1100 (decimal 12)
  12 Output.
5 print 4 & 8 ANDs these numbers, with result given:
0100 (decimal 4)
1000 (decimal 8)
0000
  0 Output.
6 print 4 ^ 4 Exclusive ORs these numbers, with result given:
0100
0100
0000
  0 Output.
Operator Precedence

When performing mathematical operations with mixed operators, it is important to note that Python determines which operations to perform first, based on a pre-determined precedence. This precedence follows a similar precedence to most programming languages. The following table shows Python precedence.

Operator Description
lambda Lambda expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in Membership tests
is, is not Identity tests
<, <=, >, >=, <>, !=, == Comparisons
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Shifts
+, - Addition and subtraction
*, /, %
Multiplication, division, remainder
+x, -x Positive, negative
~x Bitwise not
**
Exponentiation
x.attribute Attribute reference
x[index] Subscription
x[index:index] Slicing
f(arguments...) Function call
(expressions...) Binding or tuple display
[expressions...] List display
{key:datum...} Dictionary display
`expressions...` String conversion

Most of the mathematical operations you perform are probably the group in the middle, especially addition, subtraction, multiplication, division, and exponentiation.

Rather than keep track of these rules of precedence, it is better to wrap your expression in parentheses. For example, are you expecting the result of the calculation below to be 10?

2+3 * 2

It will be 8, despite the fact that visually it looks like you add the 2 + 3 together to produce 5, then multiply 5 by 2. Sorry, you fail that assignment!

Try this instead if you want 10:

(2 + 3) * 2

Or this if you want 8:

2 + (3 * 2)

Operator Examples
Line Code Meaning
1 print 2+3 * 2 Evaluating multiplication, then addition.
  8 Output.
2 print (2 + 3) * 2 Parenthesis force precedence.
  10 Output.
3 print 10 / 3 Integer division
  3 Output.
4 print 10 // 3 Integer division with integer operator
  3 Output.
5 print 10.0 / 3.0 Float division
  3.3333333333333335 Output.
6 print 10.0 // 3.0 Integer division
  3.0 Output.
7 num = 12
Setting a variable.
8 if not num > 13:
print ’num not greater than 13’
Negating a test.
This line executes.
9 if num > 10 or num < 12:
print "num > 10 or < 12"
This line executes.
10 if num > 10 and num < 12:
print "num between 11 and 12"
This line does not execute.

math Module

Python provides the math module for more complicated mathematics.

LIne Code Prints Meaning
1 import math   Importing the math module.
2 num = 10.1
  Setting a variable.
3 print math.floor(num)
  Largest integer value less than or equal to num.
  10.0   Output
4 print math.ceil(num)   Smallest integer value greater than or equal to num.
  11   Output.
5 print round(num)   Rounded float value of num.
  10.0   Output.
6 radians = math.radians(45)
  Convert degrees to radians. Python trigonometry functions uses radians, not degrees.
  0.785398163397
  Value of radians
8 print math.tan(radians)
  Tangent of a 45o angle must be 1.
  1.0   Output.
9 num = -10.1    
10 print abs(num)   Absolute value of num using built-in abs function.
  10.1   Output.
11 pi = math.pi   Setting a variable.
12 print pi   Value of pi
  3.14159265359   Output.
13 radius = 10
  Radius of a circle.
14 radiusSquared = math.pow(radius,2)    
15 areaOfCircle = pi * radiusSquared    
16 print areaOfCircle    
  314.159265359   Output.
17 print math.sqrt(256)   Square root.
  16   Output.
18 print math.log10(1000)
  Log 10 of 1000
103 = 1000
  3   Output.
19 print math.log(1024,4)   log 4 of 1024.
45 = 1024
  5   Output.

Best Practices for Numbers and Operators

Personal tools