Week 1: Introduction to Programming in Python
If possible, you should print this PDF and use it to take notes while watching the videos. For
your convenience, the numbering of sections in this document corresponds to the numbering
of videos on Blackboard. At the end of the session, you will be able to download a Jupyter
notebook version of this handout that includes solutions to all exercises.
1.1 Course Overview
This course is about applying simulation and optimization to help businesses make effective
decisions. The pedagogical focus is on the thinking process for solving difficult problems.
Reflection Question: Describe one way in which your life might improve if you master the
skills described in the video “1.1 Course Overview.” Submit your response via the Blackboard
link: Response to “1.1 Course Overview.”
1.2 Programming Basics
The essence of programming is to break down a complex task into precise steps that computers
can follow. The requisite thinking process is called algorithmic thinking. The next sections
overview the building blocks of a Python program.
Exercise for getting started: Open Jupyter notebook and create a new “Python 3” notebook.
Follow the guidance in the video “1.2 Programming Basics” to type up everything in section
1.3, including both code and Markdown cells. Submit your notebook via the Blackboard link: Get-
ting Started with Jupyter Notebook.
1.3 Objects, Types and Operators
Object: a “piece” of data.
[1]: # Examples
3
"Learning Python is fun."
True
True
Type: What “kind” of data.
[2]: type(3)
int
[3]: type("Learning Python")
str
[4]: type(True)
bool
[5]: type(3.0)
float
1
Operator: +, -, *, /, <, >, <=, >=, ==, !=, and, or, not, etc.
[6]: 3+5
[7]: 3.0+5
8.0
[8]: '3'+'2'
'32'
[9]: 'I Love Python'+'!'
'I Love Python!'
[72]: '3'+2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-72-aacce49a0307> in <module>
----> 1 '3'+2
TypeError: can only concatenate str (not "int") to str
[11]: 3==3.0
True
[12]: 3!=3.0
False
[13]: True and False
False
[14]: True or False
True
[15]: not True
False
Exercise 1.3: Exploring Operators
a) Why do you think 5==5.0 yields True, but 5==‘5’ yields False? Any explanation that you
find reasonable is fine.
b) Explain why 5+‘5’ yields an error message.
c) Using trial and error or using web search, figure out what the operator ** does.
Submit your responses via the Blackboard link: Exercise 1.3 Exploring Operators.
2
1.4 Order of Operations
(Higher Rows have Precedence)
Operator Examples
Parenthesized expressions ()
Exponentiation **
Positive/Negative +3 -2
Multiplication/Division */
Addition/Subtraction +-
Bitwise operations & \|
Comparisons < <= > >= != ==
Boolean NOT not
Boolean AND and
Boolean OR or
Assignment =
[16]: (3>2)*2**3+(4=='4')
[17]: 5.0*2>4 and 3<2
False
Exercise 1.4 Order of Operations
Without using a computer, predict the result of the following expressions. Then check your
answers using the computer.
a) 5+3**2
b) 5+(6>3)*2
c) 4*(5-(2-1))+(6==1)
d) 2*(2+1)+6/3+2**3
e) '3.1'+'4'
f) 2*4<2**3 or -3>2
g) not 3*1<2
Submit your responses via the Blackboard link: Exercise 1.4 Order of Operations.
1.5 Using Existing Functions
[18]: round(3.1425)
[19]: round(3.1425,3)
3.143
[20]: help(round)
3
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
[21]: round?
[22]: help(input)
Help on method raw_input in module ipykernel.kernelbase:
raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance
Forward raw_input to frontends
Raises
------
StdinNotImplentedError if active frontend doesn't support stdin.
[23]: input()
Hi
'Hi'
[24]: input('Enter a number: ')
Enter a number: 5
'5'
[25]: float('5')
5.0
[26]: print('You entered',5.0)
You entered 5.0
[27]: print('You entered',float(input('Enter a number: ')))
Enter a number: 5
You entered 5.0
[28]: import math
help(math.ceil)
Help on built-in function ceil in module math:
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
4
[29]: math.ceil(3.14)
[30]: help(math)
Help on module math:
NAME
math
MODULE REFERENCE
https://docs.python.org/3.7/library/math
The following documentation is automatically generated from the Python source files.
...
Exercise 1.5: Calling Functions
Submit a Jupyter notebook containing the following to the Blackboard link “1.5 Calling Functions”:
a) Pick any three functions in the math module, at least one of which has two input arguments.
For each function, write in a separate code cell an example of how to correctly call the function.
b) Write ONE line of code which uses the input function to ask the user to enter a number, and
then produce an output which is the number multiplied by 2.
1.6 Assignment to Variables and f-String Formating
The assignment s= should not be read as “s is equal to” but as “associate the name ‘s’ with the
object.”
[35]: s='Hello world'
s=s+'!'
s
'Hello world!'
[36]: num=float(input('Enter a number: '))
ans=num*2
print(num,"* 2 =",ans)
Enter a number: 5
5.0 * 2 = 10.0
Without using a computer, predict the final value of x after executing the following sequence.
x=3-1
x=x+1
x=2**x
[37]: # Example of multiple assignment
num,ans=5,10
# Example of f-string formatting
print(f'{num} * 2 = {ans}')
5
5 * 2 = 10
[38]: first=input('Enter first name: ')
last=input('Enter last name: ')
print(f'Your full name is {first} {last}.')
Enter first name: Peng
Enter last name: Shi
Your full name is Peng Shi.
Exercise 1.6: Writing a Complete Program
Download the Jupyter notebook attached to the Blackboard link “Exercise 1.6: Writing a Complete
Program” and submit it at the same link. The notebook contains the following two questions.
a) Write a program that asks the user for the quantity sold and the price per unit and multiply
them to calculate the total revenue, as in the sample run below. (Hint: you need to convert
from string to float before multiplying.)
[39]: # Write your code for Exercise 1.6-a here.
Input quantity sold: 4
Input the price per unit: 3.5
Total revenue is $14.0.
b) Write a program that calculates the present value of a certain investment, which will pay off
a cash value of C in n years. The program should ask the user to input the final cash value C,
the annual interest rate r (in percentage points), and the number of years n. The formula for
present value V is
C
V= r n
(1 + 100 )
You should round the final answer to two decimal places, as in the sample run below.
[40]: # Write your code for Exercise 1.6-b here.
Input final cash value: 1000000
Input annual interest rate in percent: 5
Input number of years: 10
The present value is $613913.25.
6
1.7 Conditional Execution
Example 1.7.1: The following program asks for the user’s systolic and diastolic blood pressure,
and output one of “LOW”, “IDEAL”, “PRE-HIGH” or “HIGH” according to this chart:
[41]: high=float(input('Systolic blood pressure: '))
low=float(input('Diastolic blood pressure: '))
if low<=60 and high<=90:
answer='LOW'
elif low<=80 and high<=120:
answer='IDEAL'
elif low<=90 and high<=140:
answer='PRE-HIGH'
else:
answer='HIGH'
print(f'Your blood pressure is {answer}.')
Systolic blood pressure: 100
Diastolic blood pressure: 70
Your blood pressure is IDEAL.
Example 1.7.2: The following program implements a primitive protocol for triaging asymp-
tomatic individuals during a pandemic.
[42]: Q1=input('Having been in one of the high risk regions in the past 14 days? (yes/no): ')
if Q1=='yes':
print('You should be quarantined for 14 days.')
else:
Q2=input('Have you been in contact with anyone who recently visited those regions? (yes/no): ')
if Q2=='yes':
print('You should consider self-quarantine for 14 days.')
else:
print("You don't need to quarantine but should practice the regular precautions.")
Having been in one of the high risk regions in the past 14 days? (yes/no): no
Have you been in contact with anyone who recently visited those regions? (yes/no): no
You don't need to quarantine but should practice the regular precautions.
7
Exercise 1.7-a: Basestock Policy in Inventory Management
Write a program that asks the user for the current inventory level.
• If the inventory is at least equal to the basestock level of 100, then output “Sufficient
inventory. No need to order.”
• Otherwise, output “Order x units”, where x is the difference between the basestock level
and the current inventory.
Current inventory: 25
Order 75 units.
Exercise 1.7-b: Payroll Calculator
Write a program that asks the user to input the number of hours worked this week, and calcu-
lates the total pay based on the following contract: for the first 40 hours, the hourly pay is 10.
Each hour worked over 40 is compensated at an increased rate of 15 per hour.
Hours worked this week: 42.5
Total pay is $437.5.
Exercise 1.7-c: Grade Conversion
Write a program that asks the user to input a numerical score, and convert it into a letter grade
based on the following table:
Score Grade
At least 90 A
At least 80 but less than 90 B
At least 70 but less than 80 C
At least 60 but less than 70 D
Less than 60 F
Enter numerical score: 95
Letter grade: A
8
1.8 Writing your own function
[46]: def add(a,b):
return a+b
[47]: add(5,3)
[48]: add(2.5,9)
11.5
[49]: help(add)
Help on function add in module __main__:
add(a, b)
[50]: def add(a,b):
'Function that returns the sum of the two input arguments. '
return a+b
[51]: help(add)
Help on function add in module __main__:
add(a, b)
Function that returns the sum of the two input arguments.
[52]: def add(a,b=1):
'''Function with two input arguments:
- a: the first argument.
- b: the second (defaults to 1).
The function returns the sum of the two arguments.
'''
return a+b
[53]: help(add)
Help on function add in module __main__:
add(a, b=1)
Function with two input arguments:
- a: the first argument.
- b: the second (defaults to 1).
The function returns the sum of the two arguments.
[54]: add(3)
9
[55]: # Returning multiple outputs
def sumAndProduct(a,b):
return a+b,a*b
[56]: s,p=sumAndProduct(5,3)
print(f'sum: {s} product: {p}')
sum: 8 product: 15
[57]: # Returning no outputs
def sumAndProduct2(a,b):
print(f'sum: {a+b} product: {a*b}')
[58]: sumAndProduct2(5,3)
sum: 8 product: 15
[59]: def bloodPressure(high,low):
'''Function that classifies a person's blood pressure.
- high: systolic pressure.
- low: diastolic pressure.
'''
if low<=60 and high<=90:
answer='LOW'
elif low<=80 and high<=120:
answer='IDEAL'
elif low<=90 and high<=140:
answer='PRE-HIGH'
else:
answer='HIGH'
return answer
[60]: print(f'100/70 is {bloodPressure(100,70)}.')
100/70 is IDEAL.
[61]: print(f'190/100 is {bloodPressure(190,100)}.')
190/100 is HIGH.
[62]: help(bloodPressure)
Help on function bloodPressure in module __main__:
bloodPressure(high, low)
Function that classifies a person's blood pressure.
- high: systolic pressure.
- low: diastolic pressure.
10
Exercise 1.8. Making your Code for 1.7 Re-Usable
a) Write a function called orderQuantity with two input arguments
• inventory (default value 0): number of items on hand.
• basestock (default value 100): the target inventory level.
If inventory is at least equal to basestock, then return 0. Otherwise, return how many items
you should order to meet the target. Include an appropriate docstring to explain what the
function does.
[64]: # Code to test your function
print('Result with no inputs:', orderQuantity())
print(f'Order {orderQuantity(25)} when inventory is 25.')
print(f'Order {orderQuantity(51,50)} when inventory is 51 and basestock is 50.')
Result with no inputs: 100
Order 75 when inventory is 25.
Order 0 when inventory is 51 and basestock is 50.
[65]: orderQuantity(basestock=200)
200
[66]: orderQuantity(inventory=80)
20
[67]: help(orderQuantity)
Help on function orderQuantity in module __main__:
orderQuantity(inventory=0, basestock=100)
Calculates order quantity given current inventory and basestock level
- inventory: number of items on hand
- basetock: the target inventory level
b) Write a function called calculateWage with three input arguments:
• hours: the number of hours worked.
• base (default value 10): the pay for each of the first 40 hours worked.
• bonus (default value 0.5): the proportional bonus for each hour worked above 40.
The function should return the total pay.
[69]: # Testing code
print('Pay for 42 hours with default base and bonus:',calculateWage(42))
print('Pay for 42 hours with base 12/hour and default bonus:',calculateWage(42,12))
print('Pay for 42 hours with base 12/hour and bonus 60%:', calculateWage(42,12,.6))
print('Pay for 42 hours with default base and bonus 50%:',calculateWage(42,bonus=0.6))
11
Pay for 42 hours with default base and bonus: 430.0
Pay for 42 hours with base 12/hour and default bonus: 516.0
Pay for 42 hours with base 12/hour and bonus 60%: 518.4
Pay for 42 hours with default base and bonus 50%: 432.0
c) Write a function called letterGrade with one input argument:
• score: the numerical score.
The function should return a string denoting the letter grade, as in Exercise 1.7.3.
[71]: # Code to test
print(f'Grade corresponding to 95 is {letterGrade(95)}.')
print(f'Grade corresponding to 80 is {letterGrade(80)}.')
print(f'Grade corresponding to 60 is {letterGrade(60)}.')
Grade corresponding to 95 is A.
Grade corresponding to 80 is B.
Grade corresponding to 60 is D.
1.9 Review
You now have what it takes to complete problem set 1, which is due at midnight (Pacific Time)
on Monday of Week 2.
12