# 2.3: Arithmetic Operations and Assignment Statements

$$\newcommand{\vecs}{\overset { \rightharpoonup} {\mathbf{#1}} }$$ $$\newcommand{\vecd}{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}}$$$$\newcommand{\id}{\mathrm{id}}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\kernel}{\mathrm{null}\,}$$ $$\newcommand{\range}{\mathrm{range}\,}$$ $$\newcommand{\RealPart}{\mathrm{Re}}$$ $$\newcommand{\ImaginaryPart}{\mathrm{Im}}$$ $$\newcommand{\Argument}{\mathrm{Arg}}$$ $$\newcommand{\norm}{\| #1 \|}$$ $$\newcommand{\inner}{\langle #1, #2 \rangle}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\id}{\mathrm{id}}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\kernel}{\mathrm{null}\,}$$ $$\newcommand{\range}{\mathrm{range}\,}$$ $$\newcommand{\RealPart}{\mathrm{Re}}$$ $$\newcommand{\ImaginaryPart}{\mathrm{Im}}$$ $$\newcommand{\Argument}{\mathrm{Arg}}$$ $$\newcommand{\norm}{\| #1 \|}$$ $$\newcommand{\inner}{\langle #1, #2 \rangle}$$ $$\newcommand{\Span}{\mathrm{span}}$$$$\newcommand{\AA}{\unicode[.8,0]{x212B}}$$

hypothes.is tag:  s20iostpy03ualr

## Learning Objectives

Students will be able to:

Content:

• Explain each Python arithmetic operator
• Explain the meaning and use of an assignment statement
• Explain the use of "+"  and "*" with strings and numbers
• Use the int()  and float() functions to convert string input to numbers for computation
• Incorporate numeric formatting into print statements
• Recognize the four main operations of a computer within a simple Python program

Process:

• Create input statements in Python
• Create Python code that performs mathematical and string operations
• Create Python code that uses assignment statements
• Create Python  code that formats numeric output

Prior Knowledge

• Understanding of Python print and input statements
• Understanding of mathematical operations
• Understanding of flowchart input symbols

## Model 1: Arithmetic Operators in Python

Python includes several arithmetic operators: addition, subtraction, multiplication, two types of division, exponentiation and mod.

Flowchart Python Program # Programmer: Monty Python
# Date: Sometime in the past
# Description: A program
# explores arithmetic operators

print(16+3)

print(16-3)

print(16*3)

print(16**3)

print(16/3)

print(16//3)

print(16.0/3)

print(16.0//3)

print(16%3)

Critical Thinking Questions:

1.  Draw a line between each flowchart symbol and its corresponding line of Python code. Make note of any problems.

2. Execute the print statements in the previous Python program

a.  Next to each print statement above, write the output.
b.  What is the value of the following line of code?

print((16//3)*3+(16%3))


c.  Predict the values of 17%3 and 18%3 without using your computer.

3.  Explain the purpose of each arithmetic operation:

a.               +          ____________________________

b.               -           ____________________________

c.               *          ____________________________

d.               **        ____________________________

e.               /           ____________________________

f.                //          ____________________________

g.                %         ____________________________

Note

An assignment statement is a line of code that uses a "=" sign. The statement stores the result of an operation performed on the right-hand side of the sign into the variable memory location on the left-hand side.

4.         Enter and execute the following lines of Python code in the editor window of your IDE (e.g. Thonny):

Python Program 1

MethaneMolMs = 16
EthaneMolMs = 30
print("The molecular mass of methane is", MethaneMolMs)
print("The molecular mass of ethane is", EthaneMolMs)

a.  What are the variables in the above python program?
b.  What does the assignment statementMethaneMolMs = 16 do?
c.  What happens if you replace the comma (,) in the print statements with a plus sign (+) and execute the code again?  Why does this happen?

5.    What is stored in memory after each assignment statement is executed? Note: Concatenating Strings in python

The "+" concatenates the two strings stored in the variables into one string.  "+" can only be used when both operators are strings.

6.         Run the following program in the editor window of your IDE (e.g. Thonny) to see what happens if you try to use the "+" with strings instead of numbers?

Python Program 2

firstName ="Monty"
lastName ="Python"
fullName = firstName + lastName
print(fullName)
print(firstName,lastName)


a.  The third line of code contains an assignment statement. What is stored in fullName when the line is executed?
b.  What is the difference between the two output lines?
c.  How could you alter your assignment statements so that print(fullName) gives the same output as print(firstName,lastName)
d. Only one of the following programs will work. Which one will work, and why doesn’t the other work? Try doing this without running the programs!

Python Program 3 Python Program 4
addressNumber = 1600
streetName = "Pennsylvania Ave"

addressNumber = "1600"
streetName = "Pennsylvania Ave"


e.  Run the programs above and see if you were correct.
f.  The program that worked above results in no space between the number and the street name. How can you alter the code so that it prints properly while using a concatenation operator?

7.  Before entering the following code into the Python interpreter (Thonny IDE editor window), predict the output of this program.

Python Program 5 Predicted Output
myNumber = "227" * 10
print(myNumber)
myWord = "Cool!" + 10
print(myWord)


Now execute it.  What is the actual output?  Is this what you thought it would do?  Explain.

8.   Let’s take a look at a python program that prompts the user for two numbers and subtracts them.

Execute the following code by entering it in the editor window of Thonny.

Python Program 6
firstNumber = input("Enter a number: ")
secondNumber = input("Enter another number: ")
difference= firstNumber - secondNumber
print("*" * 10)
print("Difference = ", difference)


a.   What output do you expect?
b.   What is the actual output
c.   Revise the program in the following manner:

• Between lines two and three add the following lines of code:
num1 = int(firstNumber)

num2 = int(secondNumber)
• Next, replace the statement:
difference = firstNumber – secondNumber
with the statement:
difference = num1 – num2
• Execute the program again. What output did you get?

d.  Explain the purpose of the function int().
e.  Explain how the changes in the program produced the desired output.

## Model 3: Formatting Output in Python

There are multiple ways to format output in python. The old way is to use the string modulo %, and the new way is with a format method function.

 Python Program 7 Output number= 1234.56789 # format with string modulo print("number = %.1f"% (number)) print("number = %.2f"% (number)) print("number = %.3f"% (number)) print("number =",format(number,'.1f')) print("number =",format(number,'.2f')) print("number =",format(number,'.3f')) print("number =",format(number,'8.1f')) print("number =",format(number,'8.2f')) print("number =",format(number,'8.3f')) 9.  Look closely at the output for python program 7.

a. How do you indicate the number of decimals to display using

the string modulo (%) ______________________________________________________

the format function ________________________________________________________

b. What happens to the number if you tell it to display less decimals than are in the number, regardless of formatting method used?

c. What type of code allows you to right justify your numbers?

10.       Execute the following code by entering it in the editor window of Thonny.

Python Program 7
numLaptops = 7
laptopCost = 599.50
price = numLaptops* laptopCost
print("Total cost of laptops: $", price)  a. Does the output look like standard output for something that has dollars and cents associated with it? b. Replace the last line of code with the following: print("Total cost of laptops:$%.2f" % price)

print("Total cost of laptops:" ,format(price, '.2f.))

Discuss the change in the output.

c.  Replace the last line of code with the following:

print("Total cost of laptops: $", format(price,'.2f') print("Total cost of laptops:$" ,format(price, '.2f.))

Discuss the change in the output.

d.  Experiment with the number ".2" in the ‘0.2f’ of the print above statement by substituting the following numbers and explain the results.

.4         ___________________________________________________

.0         ___________________________________________________

.1         ___________________________________________________

.8         ___________________________________________________

e.  Now try the following numbers in the same print statement. These numbers contain a whole number and a decimal. Explain the output for each number.

02.5     ___________________________________________________

08.2     ___________________________________________________

03.1     ___________________________________________________

f.  Explain what each part of the format function: format(variable, "%n.nf") does in a print statement where n.n represents a number.

variable ____________________________           First n _________________________

Second n_______________________                      f    _________________________

g.          Revise the print statement by changing the "f" to "d" and laptopCost = 600. Execute the statements and explain the output format.

print("Total cost of laptops: %2d" % price)
print("Total cost of laptops: %10d" % price)

h.         Explain how the function format(var,'10d') formats numeric data. var represents a whole number.

 REMINDER: Computers perform four main operations on data: Input data into a computer Output data to a screen or file Process data using arithmetic, logical, searching or sorting operations Store data

11.    Use the following program and output to answer the questions below.

Program

Program Sample Output
# Getting information
itemName=input("Enter the name of the item:  ")
numItems = int(input("Enter the number of items:  "))
itemCost = float(input("Enter the cost of one item:  "))

#Calculate price
totalCost=numItems*itemCost

#Printing results
print("Item name: ", itemName)
print("Cost of one item: ", itemCost)
print("Number of items purchased: ", numItems)
print("Total cost: $%.2f" % totalCost) a. From the code and comments in the previous program, explain how the four main operations are implemented in this program. b. There is one new function in this sample program. What is it? From the corresponding output, determine what it does. Application Questions: Use the Python Interpreter to check your work 1. Write the line of Python code that calculates and prints the answer to the following arithmetic expressions: 1. 8 to the 4th power 2. The sum of 5 and 6 multiplied by the quotient of 34 and 7 using floating point arithmetic 2. Write an assignment statement that stores the remainder obtained from dividing 87 and 8 in the variable leftover 3. Assume: courseLabel = "CHEM" courseNumber = "3350" Write a line of Python code that concatenates the label with the number and stores the result in the variable courseName. Be sure that there is a space between the course label and the course number when they are concatenated. 1. Write one line of Python code that will print the word "Happy!" one hundred times. 2. Assume: itemCost = input("Enter cost of item: ") 1. Write one line of code that calculates the cost of 15 items and stores the result in the variable totalCost 2. Write one line of code that prints the total cost with a label, a dollar sign, and exactly two decimal places. Sample output: Total cost:$22.5

3. Assume:

height1 = 67850
height2 = 456

Use Python formatting to write two print statements that will produce the following output exactly at it appears below: ## Assignment

Homework Assignment: s2020py03

1. (5 pts)  Write a Python program that prompts the user for two numbers, and then gives the sum and product of those two numbers. Your sample output should look like this:

The sum of these numbers is: 12
The product of these two numbers is: 20

• Your program must contain documentation lines that include your name, the date, a line that states "Py03 Homework question 1" and a description line that indicates what the program is supposed to do.
• Paste the code this word document and upload to your Google drive when the assignment is completed, with file name [your last name]_py03_HWQ1
• Save the program as a python file (ends with .py), with file name [your last name]_py03Q1_program and upload that to the Google Drive.

2. (10 pts) Write a program that calculates the molarity of a solution. Molarity is defined as numbers of moles per liter solvent. Your program will calculate molarity and must ask for the substance name, its molecular weight, how many grams of substance you are putting in solution, and the total volume of the solution. Report your calculated value of molarity to 3 decimal places. Your output should also be separated from the input with a line containing 80 asterixis.

Assuming you are using sodium chloride, your input and output should look like: • Your program must contain documentation lines that include your name, the date, a line that states "Py03 Homework question 2" and a description line that indicates what the program is supposed to do.
• Paste the code to question two below
• Save the program as a python file (ends with .py), with file name [your last name]_py03Q2_program and upload that to the Google Drive.

3. (4 pts) Make two hypothes.is annotations dealing with external open access resources on formatting with the format function method of formatting.  These need the tag of s20iostpy03ualr. 