### Unit 2: Operators

This unit introduces Python operators. Using the variable types introduced in Unit 1, this unit will allow us to begin computing using arithmetic, relational, and logical operators. We will also introduce operator precedence and discuss what happens when several operators are applied within a single instruction

**Completing this unit should take you approximately 4 hours.**

Upon successful completion of this unit, you will be able to:

- explain Python arithmetic operators, relational operators, logical operations, and the bool data type;
- explain operator precedence; and
- construct programs that apply variable types, operators, and operator precedence.

### 2.1: Arithmetic Operators: +, -, *, /, **, %, and //

Our programming journey begins by phrasing basic operations found on a common calculator using the syntax of our programming language, Python. In the Repl.it command line window, type these commands:

3+4 3-4 3*4 3/4

By hitting the enter key after entering each command, you can convince yourself that you now know how to use Python to add, subtract, multiply, and divide. The numbers 3 and 4 are referred to as "operands" and the +, -, *, / signs are referred to as "operators". More specifically, they are "arithmetic operators" because they are used for arithmetic. As we progress in this unit, other types of operators will be introduced.

Next, try typing the commands:

2**2 2**3

and you should see that the ** operator raises a number to a power. Recall that exponents can be positive or negative. Try typing the commands:

2**-2 2**-3

where the negative exponents compute the reciprocal of the two previous calculations. Exponents can also be fractional. For instance,

16**(1/2)

computes the square root of 16 and

8**(1/3)

computes the cube root of 8.

While these operators are useful for operating on numbers, programming applications require their use with variables. Copy and paste these commands into the Repl.it run window beginning at line 1:

a=3 print('a = ', a) print(type(a)) b=4 print('b = ', b) print(type(b)) c=a+b print(a,'+',b,' = ',c) print(type(c)) c=a-b print(a,'-',b,' = ',c) print(type(c)) c=a*b print(a,'x',b,' = ',c) print(type(c)) c=a/b print(a,'/',b,' = ',c) print(type(c)) c=a**b print(a,' to the power ',b,' = ',c) print(type(c)) a=2 print('a = ', a) b=5 print('b = ', b) c=a+b print(a,'+',b,' = ',c) c=a-b print(a,'-',b,' = ',c) c=a*b print(a,'x',b,' = ',c) c=a/b print(a,'/',b,' = ',c) c=a**b print(a,' to the power ',b,' = ',c)

Press the run button and observe the output in the command line window. Observe how the assignment operator (=) can be used to update, change, and overwrite a value contained within a variable. Also, pay close attention to the data type generated by each calculation. Initially, the variables

`a`

and`b`

are of type int. However, if the calculation results in a value that involves a decimal point, Python converts the result to the date type float. For the example above,`c=a+b`

results in a variable of type int, while`c=a/b`

overwrites a previous value and updates`c`

to a variable of type float.Lastly, we introduce two more operators, % and //, that often prove useful for working with integers:

% remainder after dividing two integers (for example, a%b)

// integer division that gives an integer result by taking the "floor" of the quotient (for example, a//b)

Clear out the commands in the run window, then copy and paste these commands into the run window beginning at line 1:

x=19 y=7 z1=x%y print('The remainder of ',x,'/',y,' = ', z1) z2=x//y print('Integer division of ',x,' and ',y, ' = ', z2)

Observe that since 19=2*7+5, the variable

`z1`

contains the remainder and`z2`

contains the floor of 19/7, which is 2.Practice these programming examples to internalize these concepts.

### 2.2: Operator Precedence and Using Parentheses

Execute these two instructions in the Repl.it command line window:

8**(1/3) 8**1/3

You should recognize the first instruction from the previous section. Observe that these instructions yield two totally different answers. The reason is that there is an order in which operators are evaluated. The "order of operations" and "operator precedence" define how arithmetic calculations are to be evaluated. As expected from basic arithmetic, exponentiation takes place before multiplication and division which take place before addition and subtraction. In addition, operations are generally read from left to right.

As an example, consider the expression

`8**1/3`

as shown above. In this case, exponentiation taking precedence over division means that`8**1`

is computed first to obtain a value of 8 and then that result is divided by 3. Hence, the final computed result is`8/3 = 2.6666...67`

. Notice that, when parentheses are added around the exponent to form`8**(1/3)`

, the exponent evaluates to`1/3`

and the cube root of 8 is computed. The term inside the parentheses has higher precedence and takes place before exponentiating. This should be a refresher about the order arithmetic expressions are evaluated in.Now, we will consider order precedence when operations are phrased within the Python programming language. Before running this set of instructions in the run window, try to predict the value each variable will contain.

a=3 b=4 c=1 d=5 e=3 f=a+b-c*d+e/d g=a+b-c*(d+e)/d h=a+(b-c)*d+e/d i=(a+b-c)*d+e/d

You may use the print statement to verify your answer.

It is important to note that // and % are considered division operations and, because of that, have precedence equal to * and /. Try to predict the value of each variable in these commands:

v=2 w=3 x=4 y=19 z=23 a=v**v//x%x+y%w*z//x b=v**(v//x)%x+y%(w*z)//x

Again, you should use insert some print commands to verify your answer.

A useful guiding principle when writing code is: if the order precedence is not clear to you by looking at the expression, use parentheses to make things obvious, since parentheses always take the highest precedence.

### 2.3: Relational and Logical Operators

The bool data type is necessary for the evaluation of logical data (which is inherently different from the numerical or string data types introduced so far). "bool" stands for Boolean data which can only take on one of two possible values: True or False. You should recall from the previous unit that True and False are reserved words within the Python language. Try executing these commands in the Repl.it run window:

a=True print(a) print(type(a)) b=False print(b) print(type(b))

You should see that True and False appear in your program as blue text indicating that they are reserved Python words. Furthermore, the data type should be identified as bool. Let's investigate how this data type can be used.

Relational operators are those that compare values in order to determine their relationship. Here is a shortlist of very useful relational operators:

**==**Equals**!=**Not Equals**>**Greater Than**<**Less Than**<=**Less Than or Equal To**>=**Greater Than or Equal To

Copy and paste these commands into the Repl.it run window:

a=2 b=3 print(a==b) print(a!=b) print(a>=b) print(a>=a) print(a<=a) print(a>b) print(a < b)

It should be clear why these are called relational operators. Also, note that the only possible answers when using these operators are either True or False.

Be EXTREMELY careful to NEVER confuse the assignment operator (=) with the relational equals (==) operator. They serve two totally different purposes. Copy and paste and run this set of commands:

a=2 b=5 a=b print(a) a=2 b=5 print(a==b)

The assignment operator assigns the numerical value contained in the variable b to the variable a. The relational operator compares the variables a and b for equality which evaluates to the bool data type False.

Finally, there are logical operators that allow us to form combinations of logical expressions. Watch the video for a description of relational and logical operators. Afterwards, you should understand these definitions for logical operators given two boolean variables x and y:

**not x**: Logical complement: if x is True, not x is False. If x is False, not x is True**x and y**: Can only be True if both x and y are True, otherwise evaluates to False**x or y**: Can only be False if both x and y are False, otherwise evaluates to True

These operators will be incredibly important in the next unit. For now, we just need to practice using them in order to get used to the syntax.

Let's try a few more in order to make sure that you are completely comfortable with the use of relational and logical operators. Copy and paste this set of commands into the Repl.it run window. Try and predict the value of each variable before running the code.

a=3 b=9 c=5 d=(a<b) and (a<c) print(d) e=(a<b) and (b<c) print(e) print(not a<b) f=(b<c) or (c<a) print(f) g=(b<c) or (c>=a) print(g)

Make sure you fully understand the output generated by these commands. The ability to mix relational and logical operators to form composite Boolean expressions is an incredibly important skill that all programmers must master.

Try these exercises for more practice with relational and logical operators.

### 2.4: Operator Precedence Revisited

Now that we have introduced arithmetic, relational and logical operators, it is important to understand their precedence when it comes to the order of operations. Here is a summary of the operators introduced so far with precedence, ordered from highest to lowest:

Parentheses** (exponentiation)*, /, //, % (multiplication and division)+, - (addition and subtraction)Relational: ==, !=, >, < , >=, <=logical notlogical andlogical orPractice running this set of commands and make sure you try to predict the variable values before looking at the answers generated.

a=3 b=9 c=5 d=(a<b) and (a<c) print(d) e= a<b and a<c print(e) f= b<c and b<a or a<c print(f) g= b<c and (b<a or a<c) print(g) h= not b<c and not b<a print(h) i= not(b<c or b<a) print(i)

Read this to learn more about operators and expressions.

### Study Session Video Review

### Unit 2 Review and Assessment

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 2. As you watch, work through the exercises to try them out yourself.

- Receive a grade
Take this assessment to see how well you understood this unit.

- This assessment
**does not count towards your grade**. It is just for practice! - You will see the correct answers when you submit your answers. Use this to help you study for the final exam!
- You can take this assessment as many times as you want, whenever you want.

- This assessment