IT 117: Intermediate Scripting
Class 2
Course Work
Python Review
Microphone
Homework 1
I have posted homework 1
here.
It is due this coming Sunday at 11:59 PM.
Unix Account and Class Directory
Some you have not created a class directory and a
Unix account.
All work for this course MUST be copied to your class directory
A directory is what you probably call a "folder".
Without a class directory you cannot submit assignments.
If you do not have a Unix account go to
http://www.cs.umb.edu/~ghoffman/linux/cs_portal.html#creating_unix_account.
If you do have a Unix account you still need a class directory
for this course.
Go to
https://portal.cs.umb.edu/accounts/login/
,
log in, click the check box for my section of this course, and click
submit.
Help with Creating a Unix Account
If you have difficulty creating an account
must get help NOW!
You can see me after class or during office hours.
You can contact me on Zoom during office hours.
Or you can contact the
Class Assistant.
Whatever it takes, you MUST create a Unix account and
a class directory.
Review Classes
This class and the two classes next week will be review classes.
I will cover the material from IT 116 that you need to know for this class.
You should use this period to brush up on your knowledge of Python.
Class Page for IT 116
You may find it useful to look at my materials for IT 116.
I have a web site where I post most of the materials for my courses.
You will find the IT 116 materials at
http://96.126.105.215/umb_classes_html/it116_html/class_page_it116.html
I have included this link on the class page for the course.
Go to the index for the Class Notes and search for a topic.
You will find the index here
http://96.126.105.215/umb_classes_html/it116_html/class_notes_it116/class_notes_index_it116.html .
Questions
Are there any questions before I begin?
Course Work
Assignments
- There are two types of assignments for this course
- Class Exercises
- Homework assignments
- In the Class Exercise you simply copy some code into a script
- The idea is to give you some practice writing and debugging Python code
- For homework assignments you write your own code
- There is a Class Exercise for each class
- There is one homework assignment each week
- All Class Exercises and homework assignments are due on the Sunday after they
are assigned
- If you miss the deadline you can still submit your scripts until the following
Saturday
- But you will lose 2 points for each day you are late
Submitting Assignments
- You will create the scripts for assignments on your machine
- But they must copied to your class directory on
pe15.cs.umb.edu
- I will only score assignments copied to your class directory on
pe15.cs.umb.edu
- You will find a link to your class directory in your Unix home directory
- In today's Class Exercise you will create two directories in your class directory
- An hw for homework assignments
- An ex directory for Class Exercises
- You must create a new directory under hw for each
homework assignment
- And you must create a new directory under ex or each
Class Exercise
- If a file is in the wrong directory or has the wrong name
you will get a 0 for the assignment
Working on Assignments
- Work on class assignments has two phases
- In the first phase you will write, test and debug the script on your machine
- In the second phase you will move the script to
pe15.cs.umb.edu
- You should also run your script on the Unix machine to make sure it works
Software for the Class
- You need different software for each phase
- For the first phase you need to download Python
- You will find instructions
here
- Python comes with a program called IDLE
- You can use IDLE to run Python statements and create scripts
- The SSH client allows you to log in to a Unix machine
- You will need it to make your script executable on the Unix machine
- And to test the assignments to make sure they run correctly
- If you have a Windows machine see
Connecting to a Unix machine from Windows
- If you have a Mac see
Connecting to a Unix machine from MacOS
- You will need FileZilla to copy your script to your class directory
- You will find instructions
here
Class Assistant
- Talia Lemerise is an undergraduate IT student
who can help you with your assignments
- You can reach her at Talia.Lemerise001@umb.edu
- You should contact the Class Assistant if you are having trouble
submitting your assignments
- I have asked the Class Assistant to schedule a Zoom seesion
each weekend to help you with any issues you might have
- You will find the details
here
Python Review
The Python Interpreter
- Python scripts are run inside the Python interpreter
- The interpreter reads the lines in a Python script statement by statement
- And runs each statement
- There are two versions of Python currently in use
- Python version 2
- Python version 3
- We will be using Python version 3.5 or greater
- It is significantly different from version 2
- You can run the Python interpreter on the Unix command line like this
$ python3
- When you do, you are using Python in
interactive mode
- This gives you a Python command line
- On this command line you can enter Python statements
- The statement will be run when you hit Enter
$ python3
Python 3.8.10 (default, Jun 2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Glenn"
>>> print(name)
Glenn
>>>
- The symbols >>> are
a prompt
- The prompt is the interpreter's way of telling you it is ready for the
next Python statement
- Noticed that the command I used to run the interpreter is
python3
- If you typed
python
instead you would get the
following error message
$ python
Command 'python' not found, did you mean:
command 'python3' from deb python3
command 'python' from deb python-is-python3
- To exit the interpreter enter
exit()
- If you are running the interpreter on the Unix command line or on a Mac you
have another option
- Hold down the Control key and hit the D key to quit
- We will not be using interactive mode much in this class
- But it is useful for experimenting with Python
Python Scripts
- All assignments for this class require you to write Python scripts
- Python scripts are text files that contain Python statements
- To create these files you must use a text editor
Rules for Scripts
- Every week I have to score three assignments
- A weekly homework assignment
- Two Class Exercises
- This is a great deal of work
- In order to speed up the scoring your scripts must follow certain rules
- You will find them here
- If you do not follow them you will lose points
- Read these rules and be sure to follow them
Variables
- A variable
is a location in the computer's memory that has a name
- And stores a single value
- In C and Java you must declare a variable before you use it
- The declaration must specify what kind of value it can hold
- If you try to put the wrong kind of value in a variable you
will get an error
- This is not true in Python
- Or other scripting languages
- You can store a string in a Python variable one moment
- Then store an integer in it at some time later
Creating Variables with Assignment Statements
Data Types
Integers and Floats
- Computers recognizes two different kinds of of numbers
- Integers are the counting numbers
1,2,3,4,5,...
- Integers are both positive and negative
..., -3,-2,-1,0,1,2,3, ...
- Floats are decimal numbers
0.0, 1.0, 1.5, 1.6, ...
- They can also be both positive and negative
- We will mostly be using integers in this class
Characters
- Everything inside a computer's memory is a binary number
- To represent a character in memory we need a way to represent them as numbers
- We do this with a table of values
- Each entry in the table contains a character and the number that stands for
that character
- Nowadays we use a character table called Unicode
- Unicode represents all the characters in most world writing systems
- But the numbers in the Unicode table can be represented inside the computer
in different formats
- These formats are called encodings
- And each encoding uses a different number of bits of to represent the number
- The most commonly used Unicode encoding is UTF-8
- You will find a listing here
Strings and String Literals
Expressions
Variable Naming Rules
Operators
Decimal and Integer Division
- Python has two division operators
- The first works like ordinary division
>>> 4 / 2
2.0
>>> 4 / 5
0.8
- Division with / always returns a float
- This is true even if the result ends in .0
- I call this decimal or normal division
- Division using // division always gives an integer
- 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 next negative integer
>>> -4 // 2
-2
>>> -5 // 2
-3
Remainder Operator
- In long division when you divide one number by another 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
- 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 when dividing by 2 is 0, the number is even
- If the remainder when dividing by 2 is 1, the number is odd
Exponent Operator
Operator Precedence
- What should Python do when you give it the following expression
2 + 3 * 5
- Should it first add 2 to 3 and then multiply the result by 5?
- Or multiply 3 by 5 and then add 2?
- Python does multiplication first
>>> 2 + 3 * 5
17
- It is doing the same thing that you were taught in arithmetic class
- The rules of arithmetic say that certain operations should be performed before others
- In computer languages the order in which operations are performed are know as rules of
operator precedence
- The operator with the highest precedence is always used first
- The precedence for Python's arithmetic operators is
** |
Exponentiation |
* / // % |
Multiplication, division and remainder |
+ - |
Addition and subtraction |
Grouping with Parentheses
- But what if we wanted to add 2 to 3 and then multiply by 5?
- We can do this by putting the expression
2 + 3
inside parentheses
>>> (2 + 3) * 5
25
- Expressions inside parentheses are always evaluated first
- Before the rules of precedence are applied
Mixed-Type Expressions and Data Type Conversion
- If you multiply two integers, you get an integer
>>> 3 * 5
15
- If you multiply two floats, you get a float
>>> 3.0 * 5.0
15.0
- But what if you multiply an integer by a float?
- In Python, you will get a float
>>> 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 int
value will be temporarily converted to a float
and the result of the operation will be a float
- An expression that uses operands of different data types is called a mixed-type expression
Escape Characters
- Not all characters produce a mark on the screen or page
- The following characters are used to put spacing between other characters
- These characters are called whitespace
- Each of these characters has its own key on the keyboard
- You type a Newline character by hitting Enter
- But what if you wanted to use these characters inside a string?
- The space would be no problem
>>> name = "Glenn Hoffman"
>>> name
'Glenn Hoffman'
- But if I tried to use a Tab instead of a space Python will object by beeping
- Trying to use a Newline is even worse
>>> name = "Glenn
File "<stdin>", line 1
name = "Glenn
^
SyntaxError: EOL while scanning string literal
- That's because these two character have special meaning in Python
- We need a special way to include these two characters inside a string
- In Python we do this by using escape characters
- You type an escape character into a string by pressing two different keys
- The first key is the backslash, \
- The second is some other character
- The most commonly used escape characters in Python are
Escape Character | Effect |
\n |
Causes output to be advanced to the next line |
\t |
Causes output to skip over to the next horizontal tab position |
\' |
Causes a single quote mark to be printed |
\" |
Causes a double quote mark to be printed |
\\ |
Causes a backslash character to be printed |
Concatenation Operator
- Addition, subtraction, multiplication and division aren't the only operations you can perform in Python
- As a matter of fact, each data type has it's own set of operations
- The most common operation you can perform between two string is joining them
- This is called
concatenation
- The concatenation operator is +
>>> first = "Glenn"
>>> last = "Hoffman"
>>> space = " "
>>> name = first + space + last
>>> name
'Glenn Hoffman'
- How does Python know what + means when you use it in an expression?
- If both of the operands are numbers it means addition
- If both are strings it means concatenation
- If one is a string and the other a number you get an error
>>> "Hello" + 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
- You can't concatenate a string and a number
- You need to convert the number into a string
- Every data type has it's own set of operators
Boolean Expression
- A value that can only be true or false is a data type called a boolean
- Python refers to this data type as
bool
- A boolean expression is an expression whose only possible values are true and false
- There are two boolean literals
- Notice the capitalization
Relational Operators
- Boolean expressions are often created using
relational operators
- Relational operators compare two values
- Essentially they answer a question about how two values relate to each other
- The relational operators are
Operator | Meaning |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
== |
Equal to |
!= |
Not equal to |
- Notice that we test for equality using ==
- not =
- This is a common mistake
- You will probably make this mistake often
- I still do
Comparing Strings
Control Structures
- A program is a series of statements
- As a program runs, the interpreter moves through the statements in a certain order
- The order in which the statements are executed is call the
flow of control
- Or the
path of execution
- In simple program the path of execution starts at the first statement
- And proceeds directly to the last statement
- To allow other paths, languages have things called
control structures
- There are two types of control structures
if
Statements
Code Blocks
- All control structures have
code blocks
- Code blocks are a series of statements that are only executed under certain conditions
- In Python you write a code block by indenting the statements from the lines above
- The statements in a code block must all be indented the same amount
- It is best to use Tabs, not spaces, when indenting code blocks
if
-else
Statements
Nested if
Statements
Testing a Series of Conditions
- Sometimes you have to check more than one condition
- Think of a program that will turn a score into a grade
- You first check whether the score is an A
- Then a B
- And so on
- Here is code that will do that
$ cat grade.py
# this programs turns a score into a letter grade
# it demonstrates using nested if statement
# to test for many possible conditions
score = int(input("What is your score? "))
print("Grade", end=" ")
if score >= 90:
print("A")
else:
if score >= 80:
print("B")
else:
if score >= 70:
print("C")
else:
if score >= 60:
print("D")
else:
print("F")
$ python3 grade.py
What is your score? 80
Grade B
$ python3 grade.py
What is your score? 60
Grade D
if
-elif
-else
Statements
- The code above will work
- But it is a little hard to read
- Notice how the code keeps shifting to the right of the page
- If the code checked for + and - grades the last clause would be way off to the right of the page
- There is a third kind of
if
statement for situations like this
- It is the
if
-elif
-else
statement
- And has the following format
if BOOLEAN_EXPRESSION_1:
STATEMENT
...
elif BOOLEAN_EXPRESSION_2:
STATEMENT
...
elif BOOLEAN_EXPRESSION_3
STATEMENT
...
...
[else:
STATEMENT
...]
- The [ ] around the
else
clause means that it is optional
- The
elif
keyword is short for "else if"
- Notice that all the
if
and elif
lines line up vertically
- This is good because it makes is clear that each condition has the same level of importance
- Here is the grade program rewritten to use the
if
-elif
-else
statement
$ cat grade2.py
# this program turns a score into a letter grade
# it demonstrates the if-elif-else statement
score = int(input("What is your score? "))
print("Grade", end=" ")
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
$ python3 grade2.py
What is your score? 50
Grade F
Logical Operators
Loops
- A loop repeats the statements in its code block a certain number of times
- The textbook calls loops repetition structures
- There are two types of loops
- Loops controlled by counting
- Loops controlled by some condition
- Counted loops stop after a certain number of iterations
- Counted loops are sometimes called
definite loops
- Conditional loops keep going as long as a condition is true
- Conditional loops are sometimes called
indefinite loops
While Loops
Infinite Loops
- A while loop stops when its boolean expression becomes false
- If it never becomes false, the loop will go on forever
- This is called an
infinite loop
- When your code goes into an infinite loop you have to abort the program
- On Unix and the Mac you do this by hitting Control C
Class Exercise
Attendance