IT 116: Introduction to Scripting
Class 13
Course Requirements
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.
Solution to Homework 5
I have posted a solution to homework 5
here.
Let's take a look.
Homework 7
I have posted homework 7
here.
It is NOT due this coming Sunday.
Instead it is due Sunday, March 24th.
This is to give you time to
study for the midterm.
And to give me time to score it.
Midterm
The Midterm exam for this course will be held on Tuesday,
March 19th.
That is the first Tuesday after the Spring Break
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 Ungraded Class
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, March 7th, 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.
Today's New Material Not on Midterm
The new material in today's class will not appear on
the Midterm.
You will only be responsible for the material in the Class Notes for the
next class.
They will cover Class Notes 2 through 12.
Quiz
There will be no graded quiz next week.
Course Requirements
Script Requirements for Functions
- The new homework assignment requires you to define functions
- When you write these function you must pay attention to the
Homework Script Rules
- Some of these requirements apply to functions
- Every function must have a comment before the header which describes
what the function does
- All function definitions must must appear at the top of the script
- The function body must contain no blank lines
- All functions definitions must have a blank line between them
- The code that runs the functions must appear at the bottom of the page ...
- after all functions have been defined
- There must be a blank line between the last function definition ...
- and the code that runs the function
- The code below shows what I mean
# this program prints some information about me
# and prints the address of our campus
# prints the address of UMB
def print_umb_address():
print("University of Massachusetts at Boston")
print("100 Morrissey Boulevard")
print("Boston, Massachusetts 02125-3393")
# prints some information about me
def print_personal_info():
print("Glenn Hoffman")
print("Information Technology Program Director")
print("Computer Science Department")
print("University of Massachusetts at Boston")
print("Glenn.Hoffman@umb.edu")
print("McCormack 3-0201-22")
print("Some information about me")
print()
print_personal_info()
print()
print_umb_address()
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 create 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
Make Sure You Body Code is Not Indented
The Two Parts of a Function Definition
Review
Local Variables
- Any time you create a variable inside a function ...
- you are creating a
local variable
- These variables are created in a special chunk of memory ...
- that comes into existence when the function is called ...
- and disappears when the function exits
- The function's bit of RAM disappears ...
- when the function finishes
- So do all it's variables
- Outside the function, the local variable does not exist
- Code outside the function cannot see it
- Local variables defined in one function are invisible to other functions
- This means we can use the same variable name ...
- in more than one function
- Another way of saying this is that the
scope
of a local variable ...
- is the function in which it is defined
Parameters
- Parameters
are a special kind of local variable
- They are defined in the
function header
inside the parentheses
- They get their values from the corresponding arguments in the
function call
- Like other local variables, they disappear after the function ends
Attendance
New Material
- The way information is presented affects how easily it can be read
- Here is another version of a script you have seen before
- It contains the same code as the original
- But looks very different
def print_umb_address():
print("University of Massachusetts at Boston")
print("100 Morrissey Boulevard")
print("Boston, Massachusetts 02125-3393")
def print_personal_info():
print("Glenn Hoffman")
print("Information Technology Program Director")
print("Computer Science Department")
print("University of Massachusetts at Boston")
print("Glenn.Hoffman@umb.edu")
print("McCormack 3-0201-22")
print("Some information about me")
print()
print_personal_info()
print()
print_umb_address()
- Although this code works, it is hard to read
- Writing code that works is not enough
- You must also write code that can be understood
- In most large companies there are coding standards
- The standards specify the format for code
- These standards are meant to improve consistency and readability
- I want you to learn good habits when writing code
- So all homework scripts must follow the
Rules for Homework Scripts
- If you do not, I will deduct points
- I have added to these rules a few that apply only to functions
- All scripts must have a comment at the top of the script
- This comment must briefly describe what the script does
- The functions must appear at the top of the file ...
- after the script comment ...
- and before the main body of the code
- Python only requires that the function definition comes before the
first call to the function
- This means the following code will run properly ...
- even though it is very hard to read
print("Some information about me")
print()
def print_umb_address():
print("University of Massachusetts at Boston")
print("100 Morrissey Boulevard")
print("Boston, Massachusetts 02125-3393")
print_umb_address()
print()
def print_personal_info():
print("Glenn Hoffman")
print("Information Technology Program Director")
print("Computer Science Department")
print("University of Massachusetts at Boston")
print("Glenn.Hoffman@umb.edu")
print("McCormack 3-0201-22")
print_personal_info()
- This is not what I want
- Each function must be preceded by a comment that tells what the
function does
- These comments must be written using #s
- There should be no blank lines after the comment
- Function comments should look like this
# prints the address of UMB
def print_umb_address():
- Not like this
# prints the address of UMB
def print_umb_address():
- There should be no blank lines inside the function body
- Don't do this
def print_umb_address():
print("University of Massachusetts at Boston")
print("100 Morrissey Boulevard")
print("Boston, Massachusetts 02125-3393")
- Do this instead
def print_umb_address():
print("University of Massachusetts at Boston")
print("100 Morrissey Boulevard")
print("Boston, Massachusetts 02125-3393")
- There must be a blank line between the end of one function
- And the start of the next
- In other words I should see this
# prints the address of UMB
def print_umb_address():
print("University of Massachusetts at Boston")
print("100 Morrissey Boulevard")
print("Boston, Massachusetts 02125-3393")
# prints some information about me
def print_personal_info():
print("Glenn Hoffman")
print("Information Technology Program Director")
print("Computer Science Department")
print("University of Massachusetts at Boston")
print("Glenn.Hoffman@umb.edu")
print("McCormack 3-0201-22")
- Not this
# prints the address of UMB
def print_umb_address():
print("University of Massachusetts at Boston")
print("100 Morrissey Boulevard")
print("Boston, Massachusetts 02125-3393")
# prints some information about me
def print_personal_info():
print("Glenn Hoffman")
print("Information Technology Program Director")
print("Computer Science Department")
print("University of Massachusetts at Boston")
print("Glenn.Hoffman@umb.edu")
print("McCormack 3-0201-22")
- There must also a blank line between the last function definition
- And the rest of the script
Default Values for Parameters
- The function call must supply a value for each parameter
- This can be very annoying if the function has many parameters
- But sometimes one of the parameters has a certain value ...
- that is used most times the function is called
- Let's look at an example
- Here is a function that converts feet and inches into inches ...
- or centimeters
# converts feet and inches to inches or centimeters
def convert(ft, in, units):
total_inches = 12 * ft + in
if units == "inches":
print(total_inches)
else:
print(total_inches * 2.54)
- When we call this function we must supply three arguments
>>> convert(6, 5, "inches")
77
- America is the only major country that does not use the metric system
- In this country the third argument would almost always be "inches"
- Having to enter a third argument which is almost always the same ...
- is very annoying
- Fortunately, Python gives you an alternative
- Python lets you define a function with a
default value
- A default value is a value that is supplied automatically ...
- if it is left out
- The format for writing a function with default values is
def FUNCTION_NAME([PARAMETER, ...], PARAMETER=DEFAULT_VALUE [, PARAMETER=DEFAULT_VALUE]):
STATEMENT
...
- Notice that the default values must come at the end of the parameter list
- You can have as many defaults as you want
- But defaults must come after the parameters that do not have defaults
- Let's rewrite the previous function to use a default value
# converts feet and inches to inches or centimeters
def convert(ft, in, units="inches"):
total_inches = 12 * ft + in
if units == "inches":
print(total_inches)
else:
print(total_inches * 2.54)
- Most calls to the function will have only two arguments
>>> convert(6, 5)
77
- But we can also supply the third argument when we need it
>>> convert(6, 5, "cm")
195.58
- With this particular function we can go a step further
- What if the measurement had no inches value?
- Only feet?
- You would still have to provide a second value
>>> convert(6, 0)
72
- Why not give the second argument a default value of 0?
def convert(ft, in=0, units="inches"):
total_inches = 12 * ft + in
if units == "inches":
print(total_inches)
else:
print(total_inches * 2.54)
- Now we can call the function with only one argument
>>> convert(6)
72
Named Arguments
- Python has an unusual feature called
named arguments
- Though the textbook calls this feature "keyword arguments"
- It let's you call a function with arguments in any order
- But you have to use the parameter name when you do it
- You write the name of the parameter ...
- followed by = ...
- followed by the value
- So instead of writing
>>> convert(6, 3, "cm")
190.5
- We can write
>>> convert(units="cm", feet=6, in=3)
190.5
- When we use named arguments we can list the arguments in any order
- But this is not the reason this feature is useful
- Many functions have multiple default values
- Lets say the function had three parameters with default values
- If you wanted to override the default for the last of these parameters
- You would have to supply values for all three parameters ...
- even if you were OK with the default values of the first two
- With named parameters you only need to override the default value ...
- for the one parameter you need to change
- Several classes ago I showed you how to change the way
print
works
- I showed you how you could turn off the automatic
newline
character ...
- that
print
automatically adds to its argument
- You do this by adding an argument of the form
end=VALUE
to print
- You can also change the space that
print
automatically
adds between its arguments ...
- to some other character or string
- You do this by adding an argument of the form
sep=VALUE
- For example
>>> a = 5
>>> b = 6
>>> c = 7
>>> print(a, b, c)
5 6 7
>>> print(a, b, c, sep=",")
5,6,7
- Both end and sep are
parameters to print that have default values
- There may be others ...
- but you do not have to worry about these others ...
- if you use named arguments
Global Variables
- Now it calls the function cheer_3
- Which creates the function's memory space
- The function has no parameters
- But it does not need any since it can see the global
variable team
- In the enclosing memory space for the script
- You can think of functions as looking at the enclosing memory ...
- through a one way mirror
- Functions can see the variables declared in the body of the program
- But the body of the program cannot see variables declared inside the function
- If I try to run of cheer_3 without
having defined team outside the function
- I will get an error
>>> cheer_3()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in cheer
NameError: name 'team' is not defined
- For this reason, it is not a good idea to use global variables inside
functions
- If you forget to define the global variable ...
- the function will not work
- Useful functions are often put into
modules
- They can then be imported into any program as needed
- Functions in a module should not depended on global variables ...
- defined inside the script
- If you did and forgot to define the global variable in the script ...
- the module function would not work
Variable Shadowing
Global Constants
Pausing Execution of a Script
Functions that Return Values
- Functions that return values can be used in assignment statements
>>> result = round(8.765)
>>> result
9
- Functions return a value using a
return statement
- Return statements have the form
return EXPRESSION
- An
expression
is anything that the Python interpreter can turn into a value
- A
return
statement does two things
- It ends the execution of the function
- It sends a value back to the function call
- A
return
statement always causes the function to quit
- So any code after the
return
statement will never be
executed
- Here is a new version of the cheer function that
returns a value
>>> def cheer_5(team):
... return "Go " + team + "!"
- To see the output we have to put a call to the function inside a call to
print
>>> print(cheer_5("Red Sox"))
Go Red Sox!
- Since cheer_5 returns a value
- A call to cheer_5 is an expression
- You can always use a function call as the argument to a
print
Returning Multiple Values
- A Python
return
statement can return more than one value
- All you have to do ...
- is follow the
return
keyword with a comma
separated list of expressions
return EXPRESION, EXPRESSION [, EXPRESSION, ...]
- Using this feature I can write a function to get both the first and
last name
>>> def get_full_name():
... first_name = input("Please enter your first name: ")
... last_name = input("Please enter your last name: ")
... return first_name, last_name
...
- When this function is called it will ask for two values ...
- and return each to a separate variable
>>> fname, lname = get_full_name()
Please enter your first name: Glenn
Please enter your last name: Hoffman
- You have to be careful when calling a function that returns more than one value
- You need a variable on the left of the assignment statement ...
- for every value the function returns
- Giving more than one variable a value in an assignment statement is called
multiple assignment
Standard Library
- Computer languages come with functions that are always available
- You don't have to do anything to use these functions
- Here are some examples from Python
- print
- int
- float
- input
- range
- They are called
built-in functions
- Built-in functions are actually part of the Python interpreter
- But Python also comes with other useful functions
- These functions are found in a set of modules called the
standard_library
- Each module in the standard library has functions and constants ...
- that deal with a specific topic
- The standard library modules are copied to your machine ...
- when you install Python
- For example, the math library contains many
mathematical functions
log | Logarithm to base e |
log10 | Logarithm to base 10 |
sin | Sine |
cos | Cosine |
tan | Tangent |
ceil |
The first integer above the argument |
- It also has some constants
pi |
The ratio of the circumference of a circle to its diameter |
e |
The base of the natural logarithms |
- To use a module you must import it with an
import
statement
- It has the following form
import MODULE_NAME
- The module name is the filename, without the .py
- To import the math module you must first write
>>> import math
Calling a Module Function
Creating Random Numbers
- Many things in nature are random
- The number of dust particles in a room
- Whether a coin comes up heads or tails
- The number of leaves in my yard
- The number of water droplets in a cloud
- Random events are things that cannot be exactly predicted
- Like whether a batter will get a hit ...
- or strike out
- We often need random numbers when writing programs
- We need them in writing
- Would a game of solitaire be any fun ...
- if the cards always appeared in the same order?
- Simulations are extremely important in many sciences
- Astronomers use simulations to study the evolution of galaxies
- Climate scientists use simulations to see what global warming will bring
- For both games and simulations we need random numbers
- But we have a problem
- Nothing that a computer does is random
- If you give a program a certain input ...
- you will always get the same output
- The output of a program is completely predictable
- There is nothing random about it
- But the need for random numbers in computing is very great
- So mathematicians have developed algorithms that create
pseudorandom numbers
- These algorithms create a sequence of numbers
- In a truly random sequence, the numbers would never repeat
- In a pseudorandom sequence the numbers eventually repeat
- But the interval between repeats is so long ...
- that they are "random" enough for most purposes
- Functions that create these sequences are called
pseudorandom number generators
- Sometimes they are simply called random number generators ...
- although that term in not really accurate
The random Module
- One of the modules in the standard library is random
- It contains several several functions that create pseudorandom numbers
- The function randint takes two integers as
arguments ...
- and returns a pseudorandom integer
- The two numbers specify the minimum and the maximum numbers created
- We can call this function several times and each time it will return a
different number
$ cat random_1.py
# demonstrates the use of the randint function of the random module
import random
for i in range(10):
print(random.randint(1,100))
$ python3 random_1.py
89
98
93
73
32
40
63
100
76
80
$ python3 random_1.py
66
49
1
29
63
17
91
3
70
5
- We can use randint to simulate throwing dice
$ cat dice.py
# this program emulates a throw of two dice
import random
die_1 = random.randint(1,6)
die_2 = random.randint(1,6)
print("You rolled", str(die_1), "and", str(die_2), "for a total of", str(die_1 + die_2))
$ python3 dice.py
You rolled 4 and 3 for a total of 7
$ python3 dice.py
You rolled 7 and 1 for a total of 8
$ python3 dice.py
You rolled 5 and 3 for a total of 8
- If we kept calling randint long enough it would
eventually repeat
- But we would have to call it a very large number of times
Other random Functions
- The random module has other pseudorandom functions
- Each of them has advantages in different situations
- The randrange function also returns an integer
- But it gives you more options when specifying the range of values
- While randint takes two arguments
- The arguments to randrange
work just like the arguments to
range
- When run with one argument randrange creates a
pseudorandom sequence ...
- with a minimum of 0 ...
- and a maximum of one less than the argument
$ cat random_2.py
# demonstrates the use of the randrange function of the random module
# with one argument
import random
for i in range(10):
print(random.randrange(5))
$ python3 random_2.py
1
3
2
0
1
1
2
2
0
4
- Notice that all the numbers are between 0 and 4
- When called with two arguments the argument specifies the minimum ...
- and the second specifies one more than the maximum
$ cat random_3.py
# demonstrates the use of the randrange function of the random module
# with two arguments
import random
for i in range(10):
print(random.randrange(1, 6))
$ python3 random_3.py
1
3
1
2
5
5
2
3
1
1
- Here all the numbers fall between 1 and 5
- When called with 3 arguments the third argument specifies the difference
between any two possible values
$ cat random_4.py
# demonstrates the use of the randrange function of the random module
# with three arguments
import random
for i in range(10):
print(random.randrange(2, 11, 2))
$ python3 random_4.py
6
6
4
6
8
10
10
4
8
2
- The values are all even numbers between 2 and 10
- Both randint and randrange
return integers
- If you want a decimal number, use random
- It generates a random number between 0.0 and 1.0
$ cat random_5.py
# demonstrates the use of the random function of the random module
import random
for i in range(10):
print(random.random())
$ python3 random_5.py
0.3366683809865726
0.6243291094221154
0.47182435685723234
0.3079697111617222
0.5048399470937616
0.11682962682702247
0.08597187089498437
0.10398098486344709
0.8667164814826076
0.15337564523669833
- uniform takes two arguments and creates decimal
numbers
- The numbers lie between the two arguments which specify the range
$ cat random_6.py
# demonstrates the use of the uniform function of the random module
import random
for i in range(10):
print(random.uniform(1, 5))
$ python3 random_6.py
3.987702460027857
2.776217942732739
2.890534381287354
1.5377836190792888
3.1461905324732022
1.010886780905638
1.4452549292653458
4.558908792372804
4.934363837349949
2.1135109420482228
Random Number Seeds
- The
algorithms
used in random need a starting value
- This starting value is called a
seed
- Each seed value generates a specific sequence of numbers
- If you keep using the same seed value ...
- you will get the same sequence of values
- To prevent this from happening the functions in
random use a trick
- Instead of choosing the same seed value each time
- They use the system time instead
- Every computer keeps track of the time and date ...
- in a variable called the system time
- The system time counts seconds
- So it is a very large integer that keeps changing
- random functions will create
different number sequences ...
- each time they are run
- But what if we wanted the sequence of numbers to be the same?
- Let's say that you were writing a simulation of a complicated system
- Say the weather over a continent
- You run the simulation once and get a result
- Then you wanted to change something about the simulation
- Say you added calculations to take account of the presence of dust in the
atmosphere
- Dust helps rain clouds form
- We would want to test this with the same sequence of as before
- We can do this using the seed function
- The seed function assigns a specific value
to the seed
- When we use the seed function to set the
seed value to the same number ...
- each time the program is run ...
- we will get the same sequence of numbers
$ cat random_6.py
# demonstrates the use of the seed function in the random module
# to generate the same series of numbers each time the program is run
import random
random.seed(67)
for i in range(10):
print(random.randint(1, 100))
$ python3 random_6.py
10
15
99
53
60
54
35
77
55
63
$ python3 random_6.py
10
15
99
53
60
54
35
77
55
63
- I use a call to seed in today's Class Exercise
- So all your scripts will have the same output
- This makes it easier for me to test
Class Exercise
Class Quiz