IT 116: Introduction to Scripting
Class 5
Today's Topics
Tips and Examples
Review
New Material
Reading Assignment
You should read Chapter 3, Decision Structures and Boolean Logic, from our
textbook, Starting Out with Python, before next weeks's class.
Homework 3
I have posted homework 3 here.
It is due this coming Sunday at 11:59 PM.
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.
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 name and be in
the correction location 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.
Tips and Examples
Help with Assignments
- A Teaching Assistant, Mohammed Najem, will have hours in the
Unix Lab to help you with your assignments
- She will be available on Monday, Wednesday and Friday from 2 PM to 4 PM
- Go here
for more information
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
- They can involve multiple steps
- When this happens, 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 the class discussion area
- 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
- Any Python variable can hold any kind of value
- And changing data type of a value assigned to a variable causes no problems in Python
- When a string is stored in memory, it's 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 by using the
input
function
input
has one argument
- The text that will prompt
the user for input
input
is used in an assignment statement like this
VARIABLE_NAME = input(PROMPT)
- When the Python gets to an assignment statement using
input
it
- Prints the prompt
- Waits for the user to enter text and hit Enter
- Stores in the variable the text entered by the user
- Here is an example
>>> team = input("Please enter a team name: ")
Please enter a team name: Red Sox
>>> print("Go", team)
Go Red Sox
- Notice that there is 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'>
- In the code above we used two assignment statements
- One to get input from the user using
input
- And another to convert the value into the right data type
- We can combine both operations into a single assignment statement
>>> number = int(input("Please enter an integer: "))
Please enter an integer: 67
>>> type(number)
<class 'int'>
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 up to the next 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
- The 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 the remainder is 0, the number is even
- If 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
- Statements are the basic unit of Python programs
- In some languages, like C and Java you have to mark the end of each statement with a semi-colon, ;
- This makes it easy to write long lines of code
- You can continue a statement onto a many lines as you want
- A statement that spans many lines ends when you come to ;
- But most statements are short
- Having to put a ; at the end of every statement is very annoying
- So Python does not do this
- A statement can be as long as you like
- But a long statement might hit the edge of your window and wrap to the next line
- Python will not care if this happens
- But it might make your code hard to read
- It's best to have all you statements no longer than a certain width
- That way you can read your code without changing the width of the window
- You can break a long Python statement into two or more lines
- You do this by hitting backslash, \, before hitting Enter
>>> print("To be or not to be. \
... That is the question.")
To be or not to be. That is the question.
- Hit Enter or Return immediately after typing \ or you will get an error
>>> print('To be or not to be. \
File "<stdin>", line 1
print('To be or not to be. \
^
SyntaxError: EOL while scanning string literal
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
- That result is in turn is multiplied by the value 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 / 3
- 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 the screen
- 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
- The program works but the answer has too many decimal places
- Fortunately, Python has a useful 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 it's a single argument
- The second argument, in blue, specifies the number of decimal points
- So the result appears with two decimal points
Attendance
Graded Quiz