IT 117: Intermediate Scripting
Class 2
Course Requirements
Course Work
Python Review
Microphone
Homework 1
I have posted homework 1
here.
It is due this coming Sunday at 11:59 PM.
Trouble?
Has anyone had any trouble registering for this class or anything else?
Today's Class
Today I will first emphasize the importance of getting
a class directory for this course.
Then I will start reviewing the material covered in IT 116.
In the following two classes I will finish the IT 116 review.
Course Requirements
Class Directory for IT 117
- In this class you will be creating Python programs on
your machine
- But they must be copied to your directory in the IT 117 class directory ...
- or I will not be able to see them
- If you registered for this class last time ...
- you should have your own directory in the class directory
- If you don't, you need to do this today
- Go to
https://portal.cs.umb.edu,
log in ...
- click the check box for my section of this course, and click submit
Course Work
Assignments
- There are two types of assignments for this course
- Class Exercises
- Homework assignments
- In the Class Exercise you simply copy some Python statements ...
- into a file on your machine
- 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
- 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
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
Software for the Class
- You must have a recent version of Python on your machine
- When you install Python you get the IDLE program
- You can use the editor built into IDLE to create your scripts ...
- or any suitable editor
- You will need FileZilla to copy your scripts to your class directory
- You will find instructions
here
- If you want to run your program on pe15.cs.umb.edu ...
- or you want to run my test script on your class exercise ...
- you need an
SSH client
- The SSH client allows you to log in to a Unix machine from your computer
- 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
Python Review
The Python Interpreter
- Python scripts are text files
- The CPU does not understand text
- It only understands its own binary machine language
- Python scripts are run inside the Python interpreter ...
- which turns the statements into machine language
- The interpreter reads the lines in a Python script statement by statement ...
- and translates each line into the binary instructions the CPU understands ...
- as it progresses through your script
- 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
Variables
- A variable
is a location in the computer's memory that has a name ...
- and holds a single value
- In C and Java you must specify what kind of value a variable will
contain ...
- before you use
- 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 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 it as a number
- 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
- All the characters in English can be represented in a
byte
...
- which has a length of 8 bits
- But Chinesee characters need multiple bytes
- So how will Python know how many bytes make a character?
- Part of the Unicode standard are a couple of encoding systems
- Each encoding system tell Python the number of bytes for each
character
- Pythone assumes uses the UTF-8 encoding
- 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 ...
- the decimal part 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 order of 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
- An expression that uses operands of different data types is called a mixed-type expression
Escape Sequences
- Not all Unicode 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 or Return
- But what if you wanted to use these characters inside a string literal?
- 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: unterminated string literal (detected at line 1)
- We need a special way to include these two characters inside a string literal
- In Python we do this by using Escape Sequences
- You type an escape sequences 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 sequences in Python are
Escape Sequence | 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 ...
- and give a boolean result
- 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
Precedence of Relational Operators
- All the relational operators have lower precedence ...
- than the arithmetic operators
- The order of precedence is
| ** |
Exponentiation |
| *
/
//
%
|
Multiplication, division and remainder |
| +
-
|
Addition and subtraction |
| >
<
>=
<=
==
!=
|
Relational Operators |
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 a simple program, the path of execution starts at the first statement ...
- and proceeds directly to the last statement
- To allow other paths, languages have features 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
- All 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
- 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
Precedence of Logical Operators
- The logical operators have lower precedence than arithmetic operators
- They also have lower precedence than the relational operators
- The order of precedence is
| ** |
Exponentiation |
| * / // % |
Multiplication, division and remainder |
| + - |
Addition and subtraction |
| > < >= <= ==
!=
|
Relational Operators |
| not |
Logical NOT |
| and |
Logical AND |
| or |
Logical OR |
- Notice that each logical operator has its own unique position ...
- in the precedence hierarchy
- So
not has higher precedence than and
- And
and has higher precedence than or
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