IT 116: Introduction to Scripting
Class 11
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.
Readings
If you have the textbook you should read Chapter 5,
Functions, from
Starting Out with Python.
Solution to Homework 4
I have posted a solution to homework 4
here.
Let's take a look.
Homework 6
I have posted homework 6
here.
It is due this coming Sunday at 11:59 PM.
Midterm
The Midterm exam for this course will be held on Tuesday,
October 22nd.
The exam will be given in this room.
It will consist of questions like those on the quizzes along with questions
asking you to write short segments of Python code.
60% of the points on this exam will consist of questions from the Graded
Quizzes.
There will be 15 of these questions, worth 4 points each.
The other 40% of points will come from four questions that ask you to
write a short segment of code.
There will be 4 of these questions worth 10 points each.
To study for the code questions you should be able to
- Write an
if
/elif
/else
statement
- Write a
while
loop
- Write a
for
loop using range
- Write a function that does not return a value
A good way to study for the code questions is to review the Class Exercises
and homework solutions.
The last class before the exam, Thursday, October 17th, will be a review session.
You will only be responsible for the material in the Class Notes for that class
on the exam.
You will find the Midterm review Class Notes
here.
If for some reason you cannot take the exam on the date mentioned above
you must contact me to make alternate arrangements.
The Midterm is given on paper.
I scan each exam paper and upload the scans to Gradescope.
I score the exam on Gradescope.
You will get an email from Gradescope with your score when I am done.
The Midterm is a closed book exam.
You are not allowed to use any resource other than what is in your head,
while taking the exam.
Cheating on the exam will result in a score of 0 and will be reported to the Administration.
Remember your Oath of Honesty.
To prevent cheating, certain rules
will be enforced during the exam.
Remember, the Midterm and Final determine 50% of your grade.
Questions
Are there any questions before I begin?
Tips and Examples
Studying for the Midterm with Flashcards
- 60% of the point on the Midterm come from Class Quiz Questions
- You can use the flashcards you created for these questions when
studying for the Midterm
- But not all Class Quiz Questions will appear on the Midterm
- If the flashcard question covers a topic not in the Midterm Review ...
- you do not have to study it for the exam
- You should remove these flashcards from your collection
Getting Your First IT Job
- Students sometimes come to me asking for advice on how to get an IT
job
- I have not had a job in industry for many years
- So I usually refer them to
Career Services
- They provide a web site called
Handshake
where companies can find interns
- In IT, as in many fields, your first job is the stepping stone
to your career in the field
- But it can be hard to find an internship or or a job
when you have no IT experience
- If this is a situation you face, there are things
you can do
- If you have a job, check with your current employer
- They must have computers somewhere and maybe you can
help keeping them running
- If they have an IT Department ask if there is something you
can do for them in your free time
- You can do something similar with local organizations
like a church, temple, mosque or youth group
- They probably use a computer for some of the work they do
or perhaps they need a web page
- Volunteer to do some IT work for them in return for a letter
talking about the work you did
- You can cite this work in your resume
- Another place to find volunteer opportunities is
Volunteer Match
- They have virtual opportunities that in many different areas
- Or perhaps you can find some open source project that needs
help
- The Free Software Foundations
is based in Boston and often needs volunteers
- Many people who are looking to hire people say they are
having a hard time ...
- finding people who take their work seriously
- Whenever you get a job, no matter how menial ...
- be sure to do your best ...
- and take the work seriously
- The economy goes through cycles and sometimes jobs are hard
to find
- Employers don't want people who don't give a damn
- Just get in the habit constantly looking for opportunities
- But above all don't give up
- When solving a problem, one of your best resources ...
- is the people you work with
- Sometimes you get you get too wrapped up in a problem ...
- and can't see something that is obvious to others
- Other times you need a function or technique ...
- that you have never used before
- Nobody in IT knows everything
- Of course you could always Google for an answer
- But someone you work with might be able to explain it ...
- saving you hours of searching
- All of us who work in IT are critically dependent on our peers
- This is why I urge all of you to keep in touch with those you
meet in your classes ...
- or on the job
- Most of the jobs I have had in my life ...
- have come from leads from people I know
- Make sure you have the email or text address of everyone
you study or work with ...
- and keep in regular contact
- Maybe go out for a beer with them one a month
- You won't regret it
A Common Error
- One of the most common errors in programming ...
- results from a simple spelling mistake
- When this happens you get an error message like this
NameError: name 'miles' is not defined
- Often student get confused when they see this
- But a careful look at the code can show the problem
min = int(input("Minimum: "))
max = int(input("Maximum: "))
print()
print("Miles\tKillometers")
print("---------------------")
for miles in range(min, max + 1):
km = round(miles * 1.60934)
print(str(mile) + "\t" + str(km))
Review
for
Loops
- The
for
loop in Python has the following format
for VARIABLE_NAME in LIST_OF_VALUES:
STATEMENT
STATEMENT
...
- Python's
for
loop works differently from for
loops
in other computer languages
- The
for
keyword
is followed by a variable
- Next comes the
in
keyword followed by a list of values
- The first value in the list is assigned to the loop variable
- It keeps that value while passing through the code block
- When execution of the code block ends ...
- the next value in the list is assigned to the loop variable
- This continues until all values are used ...
- at which point the loop ends
- Here is is a
for
loop that prints the powers of 2
$ cat powers_of_2.py
# this program uses a for loop to print the powers of 2
# from 1 to 10
for number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
value = 2 ** number
print("2 to the power", number, "is", value)
$ python3 powers_of_2.py
2 to the power 1 is 2
2 to the power 2 is 4
2 to the power 3 is 8
2 to the power 4 is 16
2 to the power 5 is 32
2 to the power 6 is 64
2 to the power 7 is 128
2 to the power 8 is 256
2 to the power 9 is 512
2 to the power 10 is 1024
- The Python
for
loop is different from the for
loop in other languages ...
- which only give integer values to the loop variable
- You can do everything with a Python
for
loop ...
- that you can do with the
for
loop in other languages
- But the Python
for
loops allows you to do more
- In Python the loop variable can be of any
data type
The range
Function
Setting the First and Last Values with range
Setting the Increment with range
Nested Loops
- Just as you can have an
if
statement inside another
if
statement
- You can have a loop inside another loop
- This is called a
nested loop
- When you nest
for
loops the name of each loop variable must
be different ...
- or you will get very strange results
- Let's write a script to create a multiplication table
$ cat times_table.py
# This script creates a times table using nested for loops
for row in range(1, 11):
for column in range(1, 11):
entry = row * column
print(entry, end="\t")
print()
$ python3 times_table.py
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
- With each pass through the outer loop the loop variable
row gets a new value
- It keeps that value while the inner loop variable
column changes from 1 to 10
Attendance
New Material
Calculating a Running Total
- If we wanted to add a series of numbers
- We might use the following
algorithm
set a variable to 0
for a number in a list of numbers
add the number to the variable
print the result
- Here is code to add the numbers from 1 to 10
>>> total = 0
>>> for number in range(1, 11):
... total = total + number
...
>>> print(total)
55
- Each time we go through the loop a new value is added to
total
- A total that is updated as new numbers are encountered ...
- is called a
running total
- A good example of a running total in everyday life is a bank balance
- Your bank balance is the running total of all deposits and withdrawals ...
- from your bank account
- Running totals are calculated using
- A variable that holds the running total
- A loop adding each new number
- The variable that holds running total is called an
accumulator
- Before you enter the loop, the accumulator must be set to 0
- Let's say you wanted to add a list of numbers entered by the user
- How can we tell when the user has finished entering numbers?
- There are many ways to do this
- One way is to ask the user how many numbers will be entered ...
- before entering the loop
- Like this
$ cat add_many_numbers.py
# adds a series of numbers entered by the user
# uses a for loop to do this after asking the user
# for the number of entries to be added
entries = int(input("How many entries? "))
total = 0
for entry_no in range(entries):
number = int(input("number: "))
total = total + number
print("Total", total)
$ python3 add_many_numbers.py
How many entries? 5
number: 34
number: 54
number: 123
number: 345
number: 55
Total 611
- The numbers in blue are user entries
- Notice that we did not use the value of the loop variable
- We simply wanted to run the loop a certain number of times
- I'll show you a much better way to do this below
Augmented Assignment Operators
- The program above contains the line
total = total + number
- This statement does the following
- Gets the current value of the variable
total
- Adds the value of number to the
current value of
total
- Assign this new value to total
- This sort of statement occurs frequently in programs
- So most languages provide a special operator
+= ...
- to use in such situations
- We can use it to rewrite the line above as
total += number
- This operator does three things
- Gets the current value of the variable on the left
- Adds the value of the expression of the right to it
- Assigns this new value to the variable on the left
- Using this new operator we can rewrite
add_many_numbers.py like this
$ cat add_many_numbers_2.py
# adds a series of numbers entered by the user
# uses a for loop to do this after asking the user
# for the number of entries to be added
entries = int(input("How many entries? "))
total = 0
for entry_no in range(entries):
number = int(input("number: "))
total += number
print("Total", total)
$ python3 add_many_numbers_2.py
How many entries? 5
number: 48
number: 243
number: 53
number: 175
number: 65
Total 584
- The += operator makes the code shorter ...
- which reduces the risk of errors
- Operators like this is called
augmented assignment operators
...
- because they do more than assign a value to a variable
- Python has an augmented assignment operator ...
- for every arithmetic operator
Operator | Example | Equivalent To |
+= |
num += 5 |
num = num + 5 |
-= |
num -= 5 |
num = num - 5 |
*= |
num *= 5 |
num = num * 5 |
/= |
num /= 5 |
num = num / 5 |
//= |
num //= 5 |
num = num // 5 |
%= |
num %= 5 |
num = num % 5 |
**= |
num **= 5 |
num = num ** 5 |
- Here are some examples
>>> number = 5
>>> number += 1
>>> number
6
>>> number -= 1
>>> number
5
>>> number *= 3
>>> number
15
>>> number = 7
>>> number /= 2
>>> number
3.5
>>> number = 7
>>> number //= 2
>>> number
3
>>> number = 7
>>> number %= 2
>>> number
1
>>> number = 2
>>> number **= 3
>>> number
8
Calculating Averages
- We use a running total when calculating averages
- The average is the total divided by the number of values
- Here is an example
$ cat average.py
# this program asks the user how many numbers
# they have to enter, then performs a running
# total and computes the average
entries = int(input("How many entries? "))
total = 0
for entry_no in range(entries):
number = int(input("number: "))
total += number
average = total / entries
print("Average", average)
$ python3 average.py
How many entries? 10
number: 10
number: 9
number: 8
number: 7
number: 6
number: 5
number: 4
number: 3
number: 2
number: 1
Average 5.5
Sentinels
- In the script above we had to ask the user for the number of values
- Before entering the loop
- This is not a good idea
- It forces that user to count the values before entering them
- In other words, we are asking the user to do extra work
- But computers are supposed to make our work easier
- A better way to know when to stop is to use a special value
- The program keeps adding entries to the total ...
- until the user enters this special value
- This special value is called a
sentinel
- Here is a program to calculate the average using 0 as a sentinel
$ cat average_3.py
# this program averages a series of numbers entered
# by the user using a sentinel to indicate the
# end of input
sentinel = 0
total = 0
entries = 0
print("Enter numbers when prompted")
print("When you are done, enter 0")
number = int(input("number: "))
while number != sentinel:
total += number
entries += 1
number = int(input("number: "))
average = total / entries
print("Average", average)
Enter numbers when prompted
When you are done, enter 0
number: 5
number: 4
number: 3
number: 2
number: 1
number: 0
Average 3.0
- We had to make a number of modifications to make this
change
- Tell the user the value to used as a
sentinel
- CHANGE the
for
loop to
a while
loop
- Create the
variable entries
initialized to 0
- Increment entries
each time through the loop
- Ask for the first number before entering the
loop
- To initialize a variable is to give it its first
value
- But we have to be careful when choosing a sentinel value
- The value cannot be one of the numbers we are averaging
- This could happen if we are calculating average temperatures
- Because 0 is a perfectly good value for temperature
- We need a number that would never occur in our list of values
- We can do this with temperatures ...
- but we have to know some physics
- No Celsius temperature can be below -273 degrees
- It is the temperature of absolute zero ...
- when all molecules are motionless
- So we could use -500 as a sentinel value
- Why use -500 when -274 would do?
- Because it is easier to remember 500 than 274
Functions
- A
function
is a group of statements that has a name ...
- and performs a specific task
- The Python interpreter has a number of functions that are always available
- You don't have to do anything special to use them
- They are called
built-in functions
...
- because they are defined inside the Python interpreter
- Python also allows you to define your own functions
- Most Python scripts contain functions that break up the work ...
- into smaller chunks of code
- If you define functions that you find yourself using over and over ...
- you can create Python files that contain these functions
- These files are called
modules
- Modules are not scripts
- If you run them, nothing will happen
- But they contain functions that other scripts can use
- To use module functions inside your script you write an
import
statement
import MODULE_NAME
- The module name is the file name without the
.py extension
- The import statement must be at the top of the script ...
- before you make any calls to its functions
- The
import
statement loads the module code into memory ...
- so the interpreter can find the definitions when you script calls
the functions
- Some modules are already on your machine
- They were loaded when Python was installed
- The interpreter knows where to find these modules
- If you create your own modules ...
- you have to let the interpreter know where to find them
- On Mac and Unix you do this by setting the
PYTHONPATH system variable
- This variable tells the interpreter where to look for the modules you create
Using Functions in Writing Programs
- What is the first thing you should do if you are given a big job?
- You should break it down into smaller tasks ...
- and then work on each one in turn
- The textbook gives an example of a program to print a check
- This job breaks down into a number of smaller tasks
- Get the hours worked
- Get the employee's hourly rate
- Calculate the gross pay
- Calculate the overtime pay
- Calculate the withholdings
- Calculate the net pay
- Print the check
- Breaking a big job into small jobs is called modularization
- It is one of the most important concepts in all of engineering
- Modularization is sometimes called "divide and conquer" ...
- or "separation of concerns"
- Without this we would never be able to do big jobs ...
- like build a bridge
- Breaking up a big task has several advantages
- We can assign each task to a different group
- This allows work to proceed in parallel
- Each group can work on its own assignment ...
- allowing many people to work on different parts of the project ...
- at the same time
- This makes the overall project work take less time
- In programming, each specific task should have its own function
- Programs that are broken up into functions are easier to read ...
- since each function each function is short ...
- and only does one thing
- This is particularly true if the function has a good name
- Modularized programs are often shorter ...
- because there is no repeated code
- You can use the same function over and over again ...
- but you only have to write it once
- Modularization makes programs easier to test
- Because you can test each function individually
- Modularization also makes it easier to work in teams
- If each function has a simple job to do ...
- one team member can work on it alone ...
- so many people can work on different parts of a project ...
- at the same time
Two Types of Functions
Function Names
Defining a Function
- A function definition has the following format
def FUNCTION_NAME([PARAMETER][...]):
STATEMENT
STATEMENT
...
- A function is a
statement
that contains other statements
- So a function is a
compound statement
- The first line of a function definition is called the
function header
- There are four parts to the function header
- The keyword
def
- The function name
- The parameter list enclosed in parentheses
- A colon, :, at the end of the line
- Parameters
are variables used inside the function
- They get their values from the arguments in the function call
- Even if the function has no parameters it must still have parentheses
- Following the function header is a series of indented statements that form a
code block
- Here is a function that prints the UMB address
# prints the address of UMB
def print_umb_address():
print("University of Massachusetts at Boston")
print("100 Morrissey Boulevard")
print("Boston, Massachusetts 02125-3393")
- This function takes no arguments
- It is also a void function since it returns no value
- Notice that I put a comment before the function definition
- It describes what the function does
- All the functions you write in homework scripts must have
such a comment
Calling a Function
- To run a function you write a
function call
- A function call has two parts
- The function name
- A list of arguments enclosed in parentheses
- You must follow the function name with parentheses ...
- even if the function takes no arguments
- That is how the interpreter knows it is a function call ...
- and not a variable name
- Here is how we would call the print_umb_address
function
print_umb_address()
Class Exercise
Class Quiz