IT 116: Introduction to Scripting
Class 12
Today's Topics
Tips and Examples
Review
New Material
Homework 6
homework 6 has been posted
It is due this coming Sunday at 11:59 PM.
Requirements for Functions
The new homework assignment requires you to define functions
When you write these function you must pay attention to the function requirements
Functions Requirements
- Function names must be a good description of what the function does
- 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
# 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('ghoffman@cs.umb.edu')
print('Science 3-92A')
print("Some information about me")
print()
print_personal_info()
print()
print_umb_address()
Tips and Examples
Writing Python Scripts with a Text Editor
- Writing scripts can be frustrating
- If you misspell a variable name leave out a colon (:)
you will get an error
- In some programming courses students write scripts using special programs Integrated Development Environments
- Or IDEs
- IDEs have features that automate some routine tasks
- They can also check for certain kinds of errors
- PyCharm is one popular IDE for Python
- They are great for people who already know Python
- But they can be a crutch
- If you cannot write Python scripts without some special program, you become dependent on it
- You will be crippled if you need to write a script quickly in some new environment
- An IT person who can't write Python without an IDE is like an outdoor guide who can't find his or her way without a GPS
- Wherever you go you will always find a text editor
- But you may not find your favorite IDE
The Command Line
- The command line is not a user friendly environment
- You might even call it user hostile
- But most serious computer problems can only be fixed at the command line
- If you want to be an IT professional you need to know your way around the command line
- That is why I insist that you use the command line in this course
- There are some problems that can be fixed using a program with nice Graphical User Interface
- But most cannot
- If you want do well in IT you need to get your hands dirty
- You need to learn to use the command line
Colorizing nano
- One way you can make writing Python scripts easier without using an IDE is to enable
syntax highlighting
- This feature makes words in Python appear in different colors depending on their meaning in the code
- Colorizing
is another name for this feature
- Here is how ex9.py appears in
nano
when colorizing is turned on
- Notice that comments appear in red
- String literals appear in green
- And keywords appear in cyan
- To turn on colorizing in
nano
you need to do the following
- Doing this will enable colorizing for files with the .py extension
- As well as Perl, PHP, bash and HTML files
- Files have the right extension for colorizing to work
Review
Calculation a Running Total
- A total that is updated as new numbers are encountered
is called a running total
- A good example of a running total is a bank balance
- Your bank balance is the running total
of all deposits and withdrawals from your account
- In programming, running totals are computed using two features
- A variable that holds the total, called the
accumulator
- And a loop in which new numbers are added to the accumulator
- Before you enter the loop, the accumulator must be set to 0
- Running totals are used when you calculate averages
$ 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
Augmented Assignment Operators
- In programming, we often have to change the value of a variable by some amount
- If we wanted to add 5 to the variable number we could write
number = number + 5
- Statements like this happen all the time
- So most computer programs have a special operator that you can use for such situations
- Instead of writing the statement above we could write
number += 5
- This operator works as follows
- Get the current value of the variable on the left
- Get the current value of the expression on the right
- Add the two values
- Assign this new value to the variable
- Using this operator makes the code shorter which reduces the risk of errors
- An operator like this is called an
augmented assignment operator
- because it does 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 |
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 you can use without doing anything special
- They are called
built-in functions
- They are written inside the Python interpreter
- You can define your own Python functions
- Most Python scripts have a number of functions inside them
- You can also create files with a number of useful functions
called modules
- If you want to use module functions in a script you need an
import
statement at the top
import MODULE_NAME
- The module name is the filename without the .py extension
- If you create a module you have to let the interpreter know where to find it
- 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
- The idea of breaking a big job into smaller tasks
is one of the most important ideas in engineering
- The formal name for this process is modularization
- But it is often referred to as "divide and conquer"
- In programming, each specific task should have its own function
- This approach has many advantages
- Programs that are broken up into functions are easier to read
- Modularized programs are usually shorter because you write a function once then use it many times
- Modularization makes programs easier to test because you can test each function individually
- Modularization also makes it easier to work in teams
- Because you can assign different functions to different people
Two Types of Functions
- There are two types of functions
- Functions that return a value
- Functions that do not return a value
- The textbook calls the second type of function a
void function
- The conversion functions like
str
, int
and float
are examples of functions that return a value
- An example of a function that does not return a function is
print
- It causes something to be printed, but it doesn't return a value
Function Names
Defining a Function
Calling a Function
- To run a function run 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
- The Python interpreter process a script statement by statement
- After a statement is processed, the interpreter forgets all about it
- Functions must be defined before they are used otherwise the interpreter will not be able to call them
- When the interpreter comes upon a function definition it stores it in a special place in memory
- When the interpreter comes across a function call it goes to that special memory location
- And executes the code block, statement by statement
- The function ends when the last statement in the code block is run
- Then interpreter returns to the line in the script where the function was called
New Material
Top Down Design
- The best way to work on a large project is to break it down into smaller tasks
- These smaller tasks can also be broken up until each task is manageable
- Programmers use this technique when writing large programs
- This technique is called top down design
- The basic approach is as follows
- Define the problem
- Break down the problem into smaller tasks
- Break down the smaller tasks into still smaller tasks
- Continue doing this until all tasks are as simple as possible
- Write functions for each of the smaller tasks
- Write a main program that calls all the functions
Example of Top Down Design
- Let's say you want to build a suspension bridge
- This is a very big project but if we break it down in smaller tasks it becomes more manageable
- Out first attempt at this might look like this
- Erect the towers
- String the cables
- Lay down the roadway
- But each of these tasks could be broken down further
- For example, erecting the towers can be broken down into
- Build the foundations
- Build the towers
- Stringing the cables could be broken down into
- Create anchorages on each bank of the river
- String the first line between the anchor points and the towers
- Run the cables from bank to bank for each cable
- Laying down the roadway can be broken down into
- Run stringers from the cable to the height of the roadway
- Erect a platform to hold the roadway suspended from the stringers
- Put a paved surface on top the the platform
- Each subtask can be broken down further
- For example building the foundation can be broken down into
- Erect a coffer dam
- Pump out the water
- Clear the bottom of mud and rubble
- Pour concrete
- With each breakdown we get closer and closer to a manageable task
- And each task can be given to a specific group of people
- Often these people can work in isolation from the rest of the project
The Advantages of Isolation
- If we are smart in how we break up the problem, each task will be independent
- It will not depend too much on the work of other teams
- That means each team can do their job without worrying about the rest of the project
- One part of building a bridge is constructing the anchors
- These massive concrete structures that hold the suspension cables taught
- There is one on either side of the river
- The teams working on the anchors not have to worry about other parts of the work
- Like the construction of the towers in the river
- Things work best when each team does is as independent of the work of others as possible
- If teams had to keep talking to one another as they worked
it would slow things down considerably
- Isolating the work of one group allows that group to keep working
- Even if other groups run into a problem
Specifying the Work for a Function
- Before you write a function you should be clear what the function should do
- Sometimes you write this out as a formal specification
- More often it is a short description in a comment before the function
- Here are comments from some of the functions I have written for use in other scripts
- converts a string into a decimal, if it can, otherwise returns the empty string
- prints an error message, then quits
- adds spaces to a string until its length is equal to the parameter given
- converts a string into an integer if it can, otherwise prints an error and quits
Keep It Simple
- One of the best ideas in engineering goes by the acronym KISS
- It stands for Keep It Simple Stupid
- Which do you think will break first?
- A machine with 10 parts or one with 100?
- The simpler something is, the less there is to go wrong
- The KISS principle says that a function should do one thing but do it well
- The more complicated you make a function, the harder it is to get it to work
Running Programs and the Operating System
- There is a special part of the operating system that deals directly with hardware
- Things like the processor, RAM and discs
- This program is called the
kernel
and it is always running in RAM
- Programs need interact with the hardware
- They need to read from a file
- Or created directories
- They cannot do this by themselves
- Instead they have to ask the kernel to do it for them
- When you are working at the command line you are running a special type of program called the
shell
- The shell allows you to ask the kernel to run a program for you
- A running program is called a
process
- And it has it's own bit of memory
- No other program can use this memory and this keeps programs from interfering with each other
- Every time you run a Python script that script is running in its own bit of RAM
How the Interpreter Uses Process Memory
- The Python interpreter runs inside the RAM for the script process
- It goes through the lines of the script statement by statement
- When it comes across a function definition it stores the code in a special part of the memory for the process
- When you create a variable in the body of the code, the value is stored somewhere else
- In another part of process memory
- When you call a function that function gets is own, separate piece of memory
- This chuck of process memory is used to store the function's variables
- It is separate from the memory where the function are stored
- The memory given to the function disappears when the function quits
- This means that the variable inside a function are not permanent
- Function memory disappears when the function finishes
- Giving each function its own space in memory keeps the function isolated from other parts of the script
Parameters
- The script cheer_1_test.py has process memory assigned to it
- The function has not been called, so there in no function memory
- When cheer_1 is called it gets its
own piece of memory for its variables
- The parameter team lives in this function memory
- team gets the value "Red Sox" from the function call
- After the function finishes it's memory disappears
- So all its variables are gone
- the script has declared the variable team in it's memory space
- When the function is called it gets it own variable memory space
- It uses this to create its own variable team
- This variable is different from the variable of the same name in the script's memory space
- When the function finishes, it gives up its memory space
- But the original variable team is still around
- It will not disappear until the script ends
Local Variables
- Once again the script has a team variable
inside it's own memory space
- Now let's look at the situation after the function is called but before any of the function code is run
- The function has no parameter, so it has no variables of its own yet
- After the first line of the function is executed a local
team variable is created
- Notice that we have two team variables with different values
- When the function finishes it loses it's memory space and all it's variables
- Now we are only left with the original team variable
- The part of a program where a variable has meaning is called the
scope of the variable
- Local variables defined inside one function are invisible outside the function
- This means we can use the same variable name in more than one function
Parameters Are Local Variables
- Parameters only come into existence inside the memory space of the function
- That means that parameters are local variables
- The only thing that makes a parameter different from other local variables it how it gets its first value
- It gets this value from an argument in the function call
- This value can be changed later, if you wish