﻿ ﻿Performing operations - Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

# Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

### 3. Performing operations

This chapter demonstrates how to use operator symbols in your code statements.

Doing arithmetic

Assigning values

Comparing values

Finding truth

Testing condition

Setting order

Summary

Doing arithmetic

The arithmetical “operators” commonly used in coding computer programs use a + symbol for addition and a - symbol for subtraction, as you would expect. Typically, they also use an * asterisk for multiplication, rather than an x symbol, and a / forward slash for division, rather than a ÷ symbol.

The arithmetical operators used to code Python programs are listed in the table below, together with the operation they perform:

 Operator: Operation: + Addition - Subtraction * Multiplication / Division % Remainder // Floor division ** Exponent

The + operator adds two numbers together and the - operator subtracts the second number from the first number.

The * operator multiplies the first number by the second number and the / operator divides the first number by the second number.

The % remainder operator divides the first number by the second number and returns 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 part from the resulting number.

The ** exponent operator returns the result of the first number raised to the power of the second number. Values used with operators to form expressions are called “operands” – in the expression 2 + 3 the numerical values 2 and 3 are the operands. arithmetic.py Start a new program by creating two variables containing whole numbers (integers)

a = 8

b = 2 Next, display the result of adding the numbers

print( ‘Addition: \t’ , a , ‘+’ , b , ‘=’ , a + b ) Now, display the result of subtracting the numbers

print( ‘Subtraction:\t’ , a , ‘-’ , b , ‘=’ , a - b ) Then, display the result of multiplying the numbers

print( ‘Multiplication:\t’ , a , ‘x’ , b , ‘=’ , a * b ) Display the result of dividing the numbers, both with and without the floating-point part

print( ‘Division: \t’ , a , ‘÷’ , b , ‘=’ , a / b )

print( ‘Floor Division:\t’ , a , ‘÷’ , b , ‘=’ , a // b ) Next, display the remainder after dividing the numbers

print( ‘Remainder:\t’ , a , ‘%’ , b , ‘=’ , a % b ) Finally, display the result of raising the first number to the power of the second number

print( ‘Exponent:\t ‘ , a , ‘² = ’ , a ** b , sep = ‘’ ) Save then run the program to see the result of the arithmetical operations  Here, the special \t character sequence 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 assignment operator commonly used in coding computer programs simply uses a = symbol to assign a value to a variable. Optionally, this may be combined with an arithmetical operator to perform arithmetic and assignment in one single operation.

The assignment operators used to code Python programs are listed in the table below together with the operation they perform:

 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, variable a is assigned the value contained in variable b – so that becomes the new value in the a variable.

The += operator is useful to add a value onto an existing value stored in the a variable – making it a combined total value.

In the example above 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 these 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 is assigned to the a variable. It is important to regard the = operator to mean “assign” rather than “equals” to avoid confusion with the == equality operator. assign.py Start a new program by creating two variables containing integer numbers and displays both assigned values

a = 8

b = 4

print( ‘Assign Values:\t’ , ’a =’ , a , ‘\tb =’ , b ) Next, add and assign a new value to the first variable and display its stored value

a += b

print( ‘Add & Assign:\t’ ,’a =’ , a , ‘\t(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 , ‘\t(12 - 4)’ )

a *= b

print( ‘Multiply & Assign:\t’ , ’a =’ , a , ‘\t(8 x 4)’ ) Finally, divide and assign a new value to the first variable and display its stored value, then remainder and assign a value to the first variable and display its stored value

a /= b

print( ‘Divide & Assign:\t’ , ’a =’ , a , ‘\t(32 ÷ 4)’ )

a %= b

print( ‘Remainder & Assign:\t’ , ’a =’ , a , ‘\t(8 % 4)’ ) Save then run the 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.

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. A-Z uppercase characters have ASCII code values 65-90 and a-z lowercase characters have ASCII code values 97-122. comparison.py Start a new program by initializing five variables with values for comparison

nil = 0

num = 0

top = 1

cap = ‘A’

low = ‘a’ 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 , ‘!=’ , top , nil != top ) Then, add statements to display the results of greater and lesser comparisons

print( ‘Greater : \t’ , nil , ‘>’ , top , nil > top )

print( ‘Lesser : \t’ , nil , ‘<’ , top , nil < top ) 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’ , top , ‘<=’ , num , top <= num ) Save then run the 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.

Finding truth

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 useful in programming to perform “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 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 programming 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). logic.py Start a new program by initializing two variables with Boolean values for logical evaluation

a = True

b = False Add statements to display the results of 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 ) Add statements to display the results of 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 ) Add statements to display the results of NOT evaluations

print( ‘\nNOT Logic:’ )

print( ‘a =’ , a , ‘\tnot a =’ , not a )

print( ‘b =’ , b , ‘\tnot b =’ , not b ) Save then 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”.

Testing condition

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

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.

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 % remainder 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. In general programming terms an “expression” always returns a value, whereas a “statement” need not – but a statement may include one or more expressions. The conditional expression has, in effect, three operands – the test expression and two possible return values. condition.py Start a new program by initializing two variables with integer values for conditional evaluation

a = 1

b = 2 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

top = 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:’ , top ) Save then run this program – to see the result of conditional expression operations  You may find that some Python programmers dislike conditional expressions as they consider its syntax contradicts the principle of easy readability.

Setting order

Operator precedence determines the order in which expressions get evaluated. For example, in the expression 3 * 8 + 4 the default order of precedence determines that multiplication with the * multiply operator is completed first, so the result is 28 (24 + 4).

The table below lists Python’s 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 % Remainder + 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 * 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. Bitwise operators are used for low-level manipulation so are omitted from this book. Identity and membership operators are introduced later but are included here for completeness. order.py Start a new program by initializing three variables with integer values for precedence comparison

a = 2

b = 4

c = 8 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 remainder 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 then 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.

Summary

•Arithmetical operators can form expressions with two operands for addition +, subtraction -, multiplication *, division /, floor division //, remainder %, or exponent **

•The % remainder operator is useful to determine whether a number is an odd or even value

•Floor division with the // operator removes any floating-point part from the result

•The assignment = operator can be combined with an arithmetical operator to perform an arithmetical calculation then assign its result

•The += operator is useful to add a value onto an existing value stored in a variable to make a combined total value

•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 - turning True to False , and vice versa

•The not operator is useful to toggle a value between True and False on successive iterations of a loop

•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 ( )

•Typically, addition + and subtraction - will be performed before multiplication * and division / unless explicitly specified

﻿