IT 116: Introduction to Scripting
Class 5
Course Work
Tips and Examples
Review
New Material
Microphone
Graded Quiz
You can connect to Gradescope to take weekly graded quiz
today during the last 15 minutes of the class.
Once you start the quiz you have 15 minutes to finish it.
You can only take this quiz today.
There is not makeup for the weekly quiz because Gradescope does not permit it.
Homework 3
I have posted homework 3 here.
It is due this coming Sunday at 11:59 PM.
Rules for Homework Scripts
You must follow certain rules when you create your homework scripts.
You will find those rules here.
Late Penalty
You will lose 2 points for every day that your assignment is late.
Every Unix file has a time stamp that changes every time the file is modified
I look at this time stamp to determine whether a submission is late.
If your assignment is not working by the due date ...
you can continue to work on it, but you will lose a few points.
If your assignment is working, do not go back and change it ...
because that will change the time stamp and result in a late penalty.
Do Not Email Me about Missing Assignments
If you get an email from me saying an assignment is missing
do not email me about this.
I get far too many emails.
Instead of sending me an email, fix the problem.
If you do not know how to fix it, post a question on Piazza ...
or contact the Class Assistant.
I collect homework assignments and and check Class Exercises several times during the week.
I will check or collect your assignment later in the week.
Class Exercises
Scripts for each Class Exercise must have the correct filename ...
and be in the right directory ...
or my scripts will not see them.
If my scripts do not see them, your score with be zero.
If you receive no email from me about your Class Exercise script ...
that means your script will get full credit ...
less any late penalty that applies.
Questions
Are there any questions before I begin?
Course Work
Importance of Exams
- I know that many of you find exams difficult
- But the best way for me to know if you have really learned
the material is by giving exams
- It is too easy to cheat on Class Exercises and homework assignments
- This is why the two exams account for 50% of your grade
- Too many students do well on the graded quizzes, Class Exercises
and homework assignment ...
- only to do poorly on the exams
- This lowers their grade considerably
- The purpose of the Class Exercises and homework assignments
is to give you hands on experience with the material
- And to better prepare you for the exams
Preparing for Exams
- Both the midterm and final exams follow the same format
- 60% of the points on the exams come from questions taken
from the ungraded class quizzes
- The remaining 40% of the points come from 4 code questions
- These questions ask you to write short segments of Python
code
- Two things will help you prepare for exams
- Flash cards
- Class Exercises and homework assignments
- Flash cards should be made for all questions from Ungraded
Class Quizzes
- You should review them frequently throughout the semester
- Pay attention when you are working on the Class Exercises and
homeworks
- Work on these assignments is teaching you how to write Python code
- This will come in handy for answering the code questions on
the midterm and final
Tips and Examples
Do Not Fall Behind in This Course
- Technical courses require that you master a great deal of detail
- You will need to study for this course several times during the week
- Studying once a week is usually not enough
- The key to success in a technical course is steady, consistant, work
- It should be spread out over several days
- Some important concepts do not sink in immediately
- It may take several days for something new to become clear
- Material in this course often depends on what came before
- So it is critical that you not fall behind
- If you fall behind, it can be VERY hard to catch up
Read the Homework Assignments Carefully
- Homework assignments may ask you to do many things
- So you may need to read the assignment more than once
- A single reading might not be enough to understand what I want you to do
- Take the time to read these documents slowly
- This will help you understand all the details
- If you don't, you will make mistakes and lose points
- Technical work is detailed work
- So you must learn to read documents with a lot of detail
- If you do not understand something post a question on Piazza
- NEVER GUESS at the meaning of something I have written
Review
Expressions
Variable Naming Rules
Choosing Good Variable Names
Numeric Data Types and Literals
- A Python variable can hold many different types of values
- Strings
- Integers
- Decimals
- Each of these types of values is stored in the computer's memory in a
different binary pattern
- The technical term for each of these different representations is a
data type
- When a string is stored in memory, its data type is
str
- When an integer is stored in memory, it has the data type
int
- When a decimal is stored, it has data type
float
- Float is short for
floating point
- Whenever we write a value directly into a Python statement ...
- that value is called a
literal
- The data type of a value determines what you can do with it
- You can add, subtract, multiply or divide integers and floats
- But you cannot divide or subtract strings
Conversion Functions
- Python has functions that convert from one data type to another
- Use
int()
to convert a value into an integer
>>> int("5")
5
- Use
str()
to convert a value into a string
>>> str(5)
'5'
- Use
float()
to convert a value into a float
>>> float("5.35")
5.35
- There are some values that cannot be converted
>>> int("five")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'five')
>>> int(7,500)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: int() base must be >= 2 and <= 36)
- A Python script can get a value from the user using the
input
function
input
has one argument
- That argument is text that will prompt
the user for input
input
is used in an assignment statement like this
VARIABLE_NAME = input(PROMPT)
- When the interpreter gets to an assignment statement using
input
it
- Prints the prompt
- Waits for the user to enter text and hit Enter
- Stores the text entered at the command line into
the variable
- Here is an example
>>> team = input("Please enter a team name: ")
Please enter a team name: Red Sox
>>> print("Go", team)
Go Red Sox
The text in blue was entered by the user
- Notice that I put a space at the end of the prompt string
- It's good to have a gap between the prompt and the value entered by the user
- The value produced by the
input
function is always a string
- This is true regardless of the value entered by the user
>>> number = input("Please enter a number: ")
Please enter a number: 55
>>> type(number)
<class 'str'>
- If you want the value to be some other data type
- You have to use a conversion function
- To convert the variable number to an integer use
the
int
function
>>> number = int(number)
>>> type(number)
<class 'int'>
- You can ask for a number and covert it using two assignment statements
- One to get input from the user with
input
...
- and another to convert the value into the right data type
- You can also combine both operations into a single assignment statement
>>> number = int(input("Please enter an integer: "))
Please enter an integer: 67
>>> type(number)
<class 'int'>
Attendance
New Material
Decimal and Integer Division
- Python has two division operators
- The first works like ordinary division
>>> 4 / 2
2.0
>>> 4 / 5
0.8
- Notice that the result is always a decimal
- Even when the result is a whole number
- This is decimal or floating-point division
- // division always gives a whole number
- When the result of the division is positive any fraction is thrown away
>>> 4 // 2
2
>>> 5 // 2
2
- When the result of the division is negative the result is rounded down
to the next lowest integer
>>> -4 // 2
-2
>>> -5 // 2
-3
Exponent Operator
Remainder Operator
- When we perform long division we get two results
- If we divide 17 by 5 we get a quotient of 3
- And a remainder of 2
- Integer division, //, gives us the quotient
>>> 17 // 5
3
- And we can get the remainder with %
>>> 17 % 5
2
- The remainder operator is sometimes called the modulus operator
- You can use the remainder operator to determine whether a number is odd or even
- If, when we divide by 2, the remainder is 0, the number is even
- If, when we divide by 2, the remainder is 1, the number is odd
Operator Precedence
Grouping with Parentheses
- But what if we wanted to perform the operations above in the order in which
they were written
- What if we wanted to first add 4 and 3
- Then multiply the result by 5
- Then square that result?
- We can use operators in an order different from the order of precedence
- We do this using parentheses, ( )
- To first add 2 + 3 then multiply by 5 we write
(4 + 3) * 5 = 35
- Parentheses are not operators
- But they override the normal order of precedence
- Calculations inside parentheses must be done first
- Before using operators outside the parentheses
- I'm told that nowadays arithmetic teachers no longer use "My Dear Aunt Sally"
- Instead they tell their student to remember PEMDAS
P - Parentheses
E - Exponent (raising to a power)
M - Multiplication
D - Division
A - Addition
S - Subtractions
- This mnemonic (memory aid) is usefully because it includes exponentiation
- But parentheses are not operators because they perform no action
Mixed-Type Expressions and Data Type Conversion
- If you multiply two integers, you get an integer
>>> 3 * 5
15
- If you multiply two decimals, you get a decimal
>>> 3.0 * 5.0
15.0
- But what if you multiply an integer by a decimal?
- In Python, you will get a decimal
>>> 3 * 5.0
15.0
- Here are the rules
- When an operation is performed on two
int
values, the result will be an int
- When an operation is performed on two
float
values, the result will be a float
- When an operation is performed on an
int
and a float
,
the result of the operation will be a float
- An expression that uses operands of different data types is called a
mixed-type expression
- If you need to convert a value into an integer you can use the
int
conversion function
- You can use
int
with strings as long as the characters are only digits
>>> int("534")
534
- But don't put a decimal point inside the string
>>> int("5.6")
Traceback (most recent call last):
File <stdin>, line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.6'
- If you run
int
on a decimal value it will throw away the digits
after the decimal point
>>> int(5.78)
5
- In other words, it does not round
- There is a
round
function for that
>>> round(5.78)
6
- If you need to convert a value into a float you can use the
float()
conversion function
- It will work with strings that contain digits and one decimal point
>>> float("5.78")
5.78
- But not two decimal points
>>> float("5.7.8")
Traceback (most recent call last):
File <stdin>, line 1, in <module>
ValueError: could not convert string to float: '5.7.8'
float
will also work with integers
>>> float(5)
5.0
Breaking Long Statements into Multiple Lines
Expressions inside Expressions
Converting Algebra Into Python
- You may have noticed that when we write the Python expression
a + b
it looks like something you saw in algebra
- But there are important difference between Python and algebra
- In algebra variable names are always a single letter
- It is legal to have a Python variable whose name is a single letter
- But it is not good practice
- Variable names should say something about the value they hold
- There are other differences
- In algebra when we write
- We mean that the value of a is multiplied by the
value of b ...
- and that result is in turn is multiplied by the value of
c
- In Python we would write this as
a * b * c
- Similarly, the algebraic expression
- would be written like this in Python
12 * 4
- The following algebraic formula
- Would look like this in Python
y = 3 * x / 2
- Similarly the formula
- in Python would be
a = (x + 12) / (13 * b)
- Notice that we had to put both the numerator
x + 12
- And the denominator
13 * b
- Inside parentheses
- We have to calculate the value of each of these expressions before dividing
them
- This is were the rules of precedence swing into action
- The financial formula
- Would become the following in Python
P = F / (1 + r) ** n
- In the formula above, P stands for present value
- In other words, the money you invest now
- F stand for how much money we want to have in
n years
- r is the interest rate
- So the formula tells you to invest P for
n years
at rate r to wind up with F
- You can see this more clearly if we give the variables meaningful names
present_value = future_value / (1.0 + rate) ** years
- To turn this formula into a script we first need three input statements
- One for each of the variables
- The
input
function returns a string
- So we will have to convert these string values into numbers
- future_value and years
will be integers
- And rate needs to be a float
- We can then calculate the present_value and print
the results
- The script looks like this
future_value = int(input("Money in the future: "))
rate = float(input("Interest rate: "))
years = int(input("Years: "))
present_value = future_value / (1.0 + rate) ** years
print("You will need to invest", present_value, "dollars at", \
rate, "interest for", years, "years")
- Notice that I used \ to split the print statement
into two lines
- I did not want the statement to be too long to fit on a single line
- When I run this script I get
python3 future_value.py
Money in the future: 1000
Interest rate: .05
Years: 10
You will need to invest 613.9132535407591 dollars at 0.05 interest for 10 years
Everything in blue is user input
- The program works, but the answer has too many decimal places
- Fortunately, Python has a function called
round
which takes one or two arguments
- If you give
round
one argument it will round to the nearest integer
>>> round(613.9132535407591)
614
- You can specify how many decimal places you want in the result with the second argument
>>> round(613.9132535407591, 2)
613.91
- The revised code looks like this
future_value = int(input("Money in the future: "))
rate = float(input("Interest rate: "))
years = int(input("Years: "))
present_value = round(future_value / (1.0 + rate) ** years, 2)
print("You will need to invest", present_value, "dollars at", \
rate, "interest for", years, "years")
- When we run it we get
$ python3 future_value.py
Money in the future: 100
Interest rate: .05
Years: 10
You will need to invest 61.39 dollars at 0.05 interest for 10 years
- The right hand side of the
assignment statement
for present_value
is very complicated
round(future_value / (1.0 + rate) ** years, 2)
- Here
round
takes two arguments
- The first argument, in red is the formula for
calculating the value needed
- Although the formula is very complicated it is a single expression
- That means its a single argument
- The second argument, in green, specifies the number
of decimal points
- So the result appears with two decimal points
Class Exercise
Class Quiz