Python in easy steps (2014)
2
Performing operations
This chapter introduces the Python operators and demonstrates the operations they can perform.
Doing arithmetic
Assigning values
Comparing values
Assessing logic
Examining conditions
Setting precedence
Casting data types
Manipulating bits
Summary
Doing arithmetic
The arithmetical operators commonly used in Python programming are listed in the table below, together with the operation they perform:
Operator: |
Operation: |
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
% |
Modulus |
// |
Floor division |
** |
Exponent |
The operators for addition, subtraction, multiplication, and division act as you would expect. Care must be taken, however, to group expressions where more than one operator is used to clarify the expression - operations within innermost parentheses are performed first. For example, with this expression:
a = b * c - d % e / f
Values used with operators to form expressions are called “operands” - in the expression 2 + 3 the numerical values 2 and 3 are the operands.
The desired order in which the operations should be performed is unclear but can be clarified by adding parentheses like this:
a = ( b * c ) - ( ( d % e ) / f )
The % modulus operator will divide the first given number by the second given number and return the remainder of the operation. This is useful to determine if a number has an odd or even value.
The // floor division operator performs just like the / division operator but truncates the result at the decimal point - removing any floating point value.
The ** exponent operator returns the result of the first operand raised to the power of the second operand.
Start a new Python script by initializing two variables with integer values
a = 8
b = 2
arithmetic.py
Next, display the result of adding the variable values
print( ‘Addition:\t’ , a , ‘+’ , b , ‘=’ , a + b )
Now, display the result of subtracting the variable values
print( ‘Subtraction:\t’ , a , ‘-’ , b , ‘=’ , a - b )
Then, display the result of multiplying the variable values
print( ‘Multiplication:\t’ , a , ‘x’ , b , ‘=’ , a * b )
Display the result of dividing the variable values both with and without the floating-point value
print( ‘Division:\t’ , a , ‘÷’ , b , ‘=’ , a / b )
print( ‘Floor Division:\t’ , a , ‘÷’ , b , ‘=’ , a // b )
Next, display the remainder after dividing the values
print( ‘Modulus:\t’ , a , ‘%’ , b , ‘=’ , a % b )
Finally, display the result of raising the first operand to the power of the second operand
print( ‘Exponent:\t ‘ , a , ‘² = ’ , a ** b , sep = ‘’ )
Save the file in your scripts directory then open a Command Prompt window there and run this program - to see the result of the arithmetical operations
The \t escape sequence shown here adds an invisible tab character to format the output.
You can use the sep parameter to explicitly specify the separation between output - here it specifies no spaces by assigning two unspaced single quote marks.
Assigning values
The operators that are used in Python programming to assign values are listed in the table below. All except the simple = assignment operator are a shorthand form of a longer expression so each equivalent is given for clarity:
Operator: |
Example: |
Equivalent: |
= |
a = b |
a = b |
+= |
a += b |
a = ( a + b ) |
-= |
a -= b |
a = ( a - b ) |
*= |
a *= b |
a = ( a * b ) |
/= |
a /= b |
a = ( a / b ) |
%= |
a %= b |
a = ( a % b ) |
//= |
a //= b |
a = ( a // b ) |
**= |
a **= b |
a = ( a ** b ) |
In the example above, the variable named “a” is assigned the value that is contained in the variable named “b” - so that becomes the new value stored in the a variable.
It is important to regard the = operator to mean “assign” rather than “equals” to avoid confusion with the == equality operator.
The += operator is useful to add a value onto an existing value that is stored in the a variable.
In the table example the += operator first adds the value contained in variable a to the value contained in variable b. It then assigns the result to become the new value stored in variable a.
All the other operators work in the same way by making the arithmetical operation between the two values first, then assigning the result of that operation to the first variable - to become its new stored value.
With the %= operator, the first operand a is divided by the second operand b then the remainder of that operation is assigned to the a variable.
Start a new Python script that initializes two variables by assigning integer values and displays both assigned values
a = 8
b = 4
print( ‘Assign Values:\t\t’ , ’a =’ , a , ‘\tb =’ , b )
assign.py
Next, add and assign a new value to the first variable and display its stored value
a += b
print( ‘Add & Assign:\t\t’ ,’a =’ , a , ‘(8 += 4)’ )
Now, subtract and assign a new value to the first variable and display its stored value, then multiply and assign a value to the first variable and display its stored value
a -= b
print( ‘Subtract & Assign:\t’ , ’a =’ , a , ‘ (12 - 4)’ )
a *= b
print( ‘Multiply & Assign:\t’ , ’a =’ , a , ‘(8 × 4)’ )
Finally, divide and assign a new value to the first variable and display its stored value, then modulus and assign a value to the first variable and display its stored value
a /= b
print( ‘Divide & Assign:\t’ , ’a =’ , a , ‘(32 ÷ 4)’ )
a %= b
print( ‘Modulus & Assign:\t’ , ’a =’ , a , ‘(8 % 4)’ )
Save the file in your scripts directory then open a Command Prompt window there and run this program - to see the result of the assignment operations
Unlike the = assign operator the == equality operator compares operands and is described here.
Comparing values
The operators that are commonly used in Python programming to compare two operand values are listed in the table below:
Operator: |
Comparative test: |
== |
Equality |
!= |
Inequality |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
The == equality operator compares two operands and will return True if both are equal in value, otherwise it will return a False value. If both are the same number they are equal, or if both are characters their ASCII code values are compared numerically to achieve the comparison result.
Conversely, the != inequality operator returns True if two operands are not equal, using the same rules as the == equality operator, otherwise it returns False. Equality and inequality operators are useful in testing the state of two variables to perform conditional branching in a program according to the result.
A-Z uppercase characters have ASCII code values 65-90 and a-z lowercase characters have ASCII code values 97-122.
The > “greater than” operator compares two operands and will return True if the first is greater in value than the second, or it will return False if it is equal or less in value. The < “less than” operator makes the same comparison but returns True if the first operand is less in value than the second, otherwise it returns False. A > “greater than” or < “less than” operator is often used to test the value of an iteration counter in a loop.
Adding the = operator after a > “greater than” or < “less than” operator makes it also return True if the two operands are exactly equal in value.
Start a new Python script by initializing five variables with values for comparison
nil = 0
num = 0
max = 1
cap = ‘A’
low = ‘a’
comparison.py
Next, add statements to display the results of numeric and character equality comparisons
print( ‘Equality :\t’ , nil , ‘==’ , num , nil == num )
print( ‘Equality :\t’ , cap , ‘==’ , low , cap == low )
Now, add a statement to display the result of an inequality comparison
print( ‘Inequality :\t’ , nil , ‘!=’ , max , nil != max )
Then, add statements to display the results of greater and lesser comparisons
print( ‘Greater :\t’ , nil , ‘>’ , max , nil > max )
print( ‘Lesser :\t’ , nil , ‘<’ , max , nil < max )
Finally, add statements to display the results of greater or equal and lesser or equal comparisons
print( ‘More Or Equal :\t’ , nil , ‘>=’ , num , nil >= num )
print( ‘Less or Equal :\t’ , max , ‘<=’ , num , max <= num )
Save the file in your scripts directory then open a Command Prompt window there and run this program - to see the result of comparison operations
The \t escape sequence shown here adds an invisible tab character to format the output.
The ASCII code value for uppercase “A” is 65 but for lowercase “a” it’s 97 - so their comparison here returns False.
Assessing logic
The logical operators most commonly used in Python programming are listed in the table below:
Operator: |
Operation: |
and |
Logical AND |
or |
Logical OR |
not |
Logical NOT |
The logical operators are used with operands that have Boolean values of True or False, or are values that convert to True or False.
The (logical AND) and operator will evaluate two operands and return True only if both operands themselves are True. Otherwise the and operator will return False. This is used in conditional branching where the direction of a program is determined by testing two conditions - if both conditions are satisfied, the program will go in a certain direction, otherwise it will take a different direction.
Unlike the and operator that needs both operands to be True, the (logical OR) or operator will evaluate its two operands and return True if either one of the operands itself returns True. If neither operand returns True then the or operator will return False. This is useful in Python programming to perform a certain action if either one of two test conditions has been met.
The (logical NOT) not operator is a unary operator that is used before a single operand. It returns the inverse value of the given operand so if the variable a had a value of True then not a would have a value of False. The not operator is useful in Python programs to toggle the value of a variable in successive loop iterations with a statement like a = not a. This ensures that on each iteration of the loop, the Boolean value is reversed, like flicking a light switch on and off.
The term “Boolean” refers to a system of logical thought developed by the English mathematician George Boole (1815-1864).
Start a new Python script by initializing two variables with Boolean values for logical evaluation
a = True
b = False
logic.py
Next, add statements to display the results of logical AND evaluations
print( ‘AND Logic:’ )
print( ‘a and a =’ , a and a )
print( ‘a and b =’ , a and b )
print( ‘b and b =’ , b and b )
Now, add statements to display the results of logical OR evaluations
print( ‘\nOR Logic:’ )
print( ‘a or a =’ , a or a )
print( ‘a or b =’ , a or b )
print( ‘b or b =’ , b or b )
Finally, add statements to display the results of logical NOT evaluations
print( ‘\nNOT Logic:’ )
print( ‘a =’ , a , ‘\tnot a =’ , not a )
print( ‘b =’ , b , ‘\tnot b =’ , not b )
Save the file in your scripts directory then open a Command Prompt window there and run this program - to see the result of logic operations
In Python programming Boolean values can also be represented numerically where True is 1 and False is 0 (zero).
Note that the expression False and False returns False, not True - perhaps demonstrating the maxim “two wrongs don’t make a right”.
Examining conditions
Many programming languages, such as C++ or Java, have a ?: “ternary” operator that evaluates an expression for a True or False condition then returns one of two specified values depending on the result of the evaluation. A ?: ternary operator has this syntax:
( test-expression ) ? if-true-return-this : if-false-return-this
In general programming terms an “expression” always returns a value whereas a “statement” need not - but a statement may include one or more expressions.
Unlike other programming languages, Python does not have a ?: ternary operator but has instead a “conditional expression” that works in a similar way using if and else keywords with this syntax:
if-true-return-this if ( test-expression ) else if-false-return-this
Although the conditional expression syntax can initially appear confusing, it is well worth becoming familiar with this expression as it can execute powerful program branching with minimal code. For example, to branch when a variable is not a value of one:
if-true-do-this if ( var != 1 ) else if-false-do-this
The conditional expression can be used in Python programming to assign the maximum or minimum value of two variables to a third variable. For example, to assign a minimum like this:
c = a if ( a < b ) else b
The expression in parentheses returns True when the value of variable a is less than that of variable b - so in this case the lesser value of variable a gets assigned to variable c.
The conditional expression has in effect three operands - the test expression and two possible return values.
Similarly, replacing the < less than operator in the test expression with the > greater than operator would assign the greater value of variable b to variable c.
Another common use of the conditional expression incorporates the % modulus operator in the test expression to determine if the value of a variable is an odd number or an even number:
if-true(odd)-do-this if ( var % 2 != 0 ) else if-false(even)-do-this
Where the result of dividing the variable value by two does leave a remainder the number is odd - where there is no remainder the number is even. The test expression ( var % 2 == 1 ) would have the same effect but it is preferable to test for inequality - it’s easier to spot when something is different than when it’s identical.
Start a new Python script by initializing two variables with integer values for conditional evaluation
a = 1
b = 2
condition.py
Next, add statements to display the results of conditional evaluation - describing the first variable’s value
print( ‘\nVariable a Is :’ , ‘One’ if ( a == 1 ) else ‘Not One’ )
print( ‘Variable a Is :’ , ‘Even’ if ( a % 2 == 0 ) else ‘Odd’ )
Now, add statements to display the results of conditional evaluation - describing the second variable’s value
print( ‘\nVariable b Is :’ , ‘One’ if ( b == 1 ) else ‘Not One’ )
print( ‘Variable b Is :’ , ‘Even’ if ( b % 2 == 0 ) else ‘Odd’ )
Then, add a statement to assign the result of a conditional evaluation to a new variable
max = a if ( a > b ) else b
Finally, add a statement to display the assigned result - identifying the greater of the two variable values
print( ‘\nGreater Value Is:’ , max )
Save the file in your scripts directory then open a Command Prompt window there and run this program - to see the result of conditional expression operations
You may find that some Python programmers dislike conditional expressions as they consider their syntax contradicts the principle of easy readability.
Setting precedence
Operator precedence determines the order in which the Python interpreter evaluates expressions. For example, in the expression 3 * 8 + 4 the default order of precedence determines that multiplication is completed first, so the result is 28 (24 + 4).
The * multiply operator is on a higher row than the + addition operator - so in the expression 3 * 8 + 4 multiplication is completed first, before the addition.
The table below lists operator precedence in descending order - those on the top row have highest precedence, those on lower rows have successively lower precedence. The precedence of operators on the same row is chained Left-To-Right:
Operator: |
Description: |
** |
Exponent |
+ |
Positive |
- |
Negative |
~ |
Bitwise NOT |
* |
Multiplication |
/ |
Division |
// |
Floor division |
% |
Modulus |
+ |
Addition |
- |
Subtraction |
| |
Bitwise OR |
^ |
Bitwise XOR |
& |
Bitwise AND |
>> |
Bitwise right shift |
<< |
Bitwise left shift |
>, >=, <, <=, ==, != |
Comparison |
= , %= , /= , //= , -= , += , *= , **= |
Assignment |
is , is not |
Identity |
in , not in |
Membership |
not |
Boolean NOT |
and |
Boolean AND |
or |
Boolean OR |
The bitwise, identity, and membership operators are introduced later in this book - but are included here for completeness.
Start a new Python script by initializing three variables with integer values for precedence comparison
a = 2
b = 4
c = 8
precedence.py
Next, add statements to display the results of default precedence and forcing addition before multiplication
print( ‘\nDefault Order:\t’, a, ‘*’, c,’+’, b, ‘=’, a * c + b )
print( ‘Forced Order:\t’, a, ‘* (‘, c,’+’, b, ‘) =’, a * ( c + b ) )
Now, add statements to display the results of default precedence and forcing subtraction before division
print( ‘\nDefault Order:\t’, c, ‘//’, b, ‘-’, a, ‘=’, c // b - a )
print( ‘Forced Order:\t’, c, ‘// (‘, b,’-’, a, ‘) =’, c // ( b - a ) )
Finally, add statements to display the results of default precedence and forcing addition before modulus operation and before exponent operation
print( ‘\nDefault Order:\t’, c, ‘%’, a, ‘+’, b, ‘=’, c % a + b )
print( ‘Forced Order:\t’, c, ‘% (‘, a, ‘+’, b, ‘) =’, c % ( a + b ) )
print( ‘\nDefault Order:\t’, c, ‘**’, a, ‘+’, b, ‘=’, c ** a + b )
print( ‘Forced Order:\t’, c, ‘** (‘, a, ‘+’, b, ‘) =’, c ** ( a + b ) )
Save the file in your scripts directory then open a Command Prompt window there and run this program - to see the results of default and explicit precedence
The // floor division operator truncates floating point values at the decimal point - but the / division operator retains them.
Do not rely upon default precedence - always use parentheses to clarify your expressions.
Casting data types
Although Python variables can store data of any data type it is important to recognize the different types of data they contain to avoid errors when manipulating that data in a program. There are several Python data types but by far the most common ones are str (string), int (integer), and float(floating-point).
Data type recognition is especially important when assigning numeric data to variables from user input as it is stored by default as a str (string) data type. String values cannot be used for arithmetical expressions as attempting to add string values together simply concatenates (joins) the values together rather than adding them numerically. For example ‘8’ + ‘4’ = ‘84’.
Fortunately, the data type of stored values can be easily converted (“cast”) into a different data type using built-in Python functions. The value to be converted is specified within the parentheses that follow the function name. Casting str (string) values to become int (integer) values allows them to be used for arithmetical expressions, for example, 8 + 4 = 12.
Python’s built-in data type conversion functions return a new object representing the converted value and those conversion functions most frequently used are listed in the table below:
Function: |
Description: |
int( x ) |
Converts x to an integer whole number |
float( x ) |
Converts x to a floating-point number |
str( x ) |
Converts x to a string representation |
chr( x ) |
Converts integer x to a character |
unichr( x ) |
Converts integer x to a Unicode character |
ord( x ) |
Converts character x to its integer value |
hex( x ) |
Converts integer x to a hexadecimal string |
oct( x ) |
Converts integer x to an octal string |
Converting a float (floating-point) data type to an int (integer) data type will truncate the number at the decimal point losing the fraction.
The Python built-in type() function can be used to determine to which data type class the value contained in a variable belongs, simply by specifying that variable’s name within its parentheses.
Start a new Python script by initializing two variables with numeric values from user input
a = input( ‘Enter A Number: ‘ )
b = input( ‘Now Enter Another Number: ‘ )
cast.py
Next, add statements to add the variable values together then display the combined result and its data type - to see a concatenated string value result
sum = a + b
print( ‘\nData Type sum :’ , sum , type( sum ) )
Now, add statements to add cast variable values together then display the result and its data type - to see a total integer value result
sum = int( a ) + int( b )
print( ‘Data Type sum :’ , sum , type( sum ) )
Then, add statements to cast a variable value then display the result and its data type - to see a total float value
sum = float( sum )
print( ‘Data Type sum :’ , sum , type( sum ) )
Finally, add statements to cast an integer representation of a variable value then display the result and its data type - to see a character string value
sum = chr( int( sum ) )
print( ‘Data Type sum :’ , sum , type( sum ) )
Save the file in your scripts directory then open a Command Prompt window there and run this program - to see the result of casting as various data types
The number 65 is the ASCII character code for uppercase letter A.
Manipulating bits
In computer terms each byte comprises eight bits that can each contain a 1 or a 0 to store a binary number representing decimal values from 0 to 255. Each bit contributes a decimal component only when that bit contains a 1. Components are designated right-to-left from the “Least Significant Bit” (LSB) to the “Most Significant Bit” (MSB). The binary number in the bit pattern below is 00110010 and represents the decimal number 50 (2+16+32):
Bit No. |
8 |
7 |
6 |
5 |
4 |
3 |
2 |
1 |
Decimal |
128 |
64 |
32 |
16 |
8 |
4 |
2 |
1 |
Binary |
0 |
0 |
1 |
1 |
0 |
0 |
1 |
0 |
Many Python programmers never use bitwise operators but it is useful to understand what they are and how they may be used.
It is possible to manipulate individual parts of a byte using the Python “bitwise” operators listed and described below:
Operator: |
Name: |
Binary number operation: |
| |
OR |
Return a 1 in each bit where either of two compared bits is a 1 |
& |
AND |
Return a 1 in each bit where both of two compared bits is a 1 |
~ |
NOT |
Return a 1 in each bit where neither of two compared bits is a 1 |
^ |
XOR |
Return a 1 in each bit where only one of two compared bits is a 1 |
<< |
Shift |
Move each bit that is a 1 a specified number of bits to the left |
>> |
Shift |
Move each bit that is a 1 a specified number of bits to the right |
Each half of a byte is known as a “nibble” (4 bits). The binary numbers in the examples in the table describe values stored in a nibble.
Unless programming for a device with limited resources there is seldom a need to utilize bitwise operators, but they can be useful. For instance, the XOR (eXclusive OR) operator lets you exchange values between two variables without the need for a third variable.
bitwise.py
Start a new Python script by initializing two variables with numeric values and display these initial values
a = 10
b = 5
print( ‘a =’ , a , ‘\tb = ‘ , b )
Next, add a statement to change the first variable’s decimal value by binary bit manipulation
# 1010 ^ 0101 = 1111 (decimal 15)
a = a ^ b
Now, add a statement to change the second variable’s decimal value by binary bit manipulation
# 1111 ^ 0101 = 1010 (decimal 10)
b = a ^ b
Then, add a statement to change the first variable’s decimal value once more by further bit manipulation
# 1111 ^ 1010 = 0101 (decimal 5)
a = a ^ b
Finally, add a statement to display the exchanged values
print( ‘a =’ , a , ‘\tb = ‘ , b )
Save the file in your scripts directory then open a Command Prompt window there and run this program - to see the result of bitwise operations
Do not confuse bitwise operators with logical operators. Bitwise operators compare binary numbers, whereas logical operators evaluate Boolean values.
Summary
•Arithmetical operators can form expressions with two operands for addition +, subtraction -, multiplication *, division /, floor division //, modulus %, or exponent **
•The assignment = operator can be combined with an arithmetical operator to perform an arithmetical calculation then assign its result
•Comparison operators can form expressions comparing two operands for equality ==, inequality !=, greater >, lesser <, greater or equal >=, and lesser or equal <= values
•Logical and and or operators form expressions evaluating two operands to return a Boolean value of True or False
•The logical not operator returns the inverse Boolean value of a single operand
•A conditional if-else expression evaluates a given expression for a Boolean True or False value then returns one of two operands depending on its result
•Expressions containing multiple operators will execute their operations in accordance with the default precedence rules unless explicitly determined by the addition of parentheses ( )
•The data type of a variable value can be converted to a different data type by the built-in Python functions int(), float(), and str() to return a new converted object
•Python’s built-in type() function determines to which data type class a specified variable belongs
•Bitwise operators OR |, AND &, NOT ~, and XOR ^ each return a value after comparison of the values within two bits, whereas the Shift left << and Shift right >> operators move the bit values a specified number of bits in their direction