IT 116: Introduction to Scripting
Class 6
General Advice
Tips and Examples
Review
New Material
Microphone
Questions
Are there any questions before I begin?
Quiz 1
I have posted the answers to Quiz 1
here.
Homework 3
I have posted homework 3
here.
It is due this coming Sunday at 11:59 PM.
Let's take a look at it.
Today's Class
General Advice
Attending Class
- One of the simplest thing you can do to improve your grades ...
- is to come to class regularly
- This is why attendance is 5% of your grade
- Studies have shown that you learn more by attending class ...
- than by taking online courses
- Teachers noticed a dramatic decline in student performance
during the COVID lockdownb...
- when schools switched from classrooms to online teaching
- Why?
- Humans are social animals
- We must have contact with other people or we go nuts
- There are large parts of our brains that help us deal with others
- For example, there is a special part of our brains that recognize
faces
- We pay more when we are with people ...
- than when we only see them on a screen
- Learning is a social experience
- While being in a classroom is better than viewing on line ...
- you learn even more when you interact with others in class
- That is why it is so important for you to ask questions in class
- If mine is the only voice you hear in class ...
- it will not be as interesting as when you hear other students speak
- Don't be afraid to ask questions in class
- You don't even have to raise your hand
- I am comfortable with interruptions
- It makes the class more interesting for me too
- If I don't know the answer I will tell you
- I may look up the answer after class ...
- and tell you what I have found in the next class
- Let's keep things lively ...
- so learning won't be a chore
Tips and Examples
Converting Decimal to Integer
Resources
- The Resources page has links that
you might find useful
- There is a link to it on the class web page
Review
Operators
Decimal and Integer Division
- Python has two division operators
- The first works like ordinary division
>>> 4 / 2
2.0
>>> 4 / 5
0.8
- Notice that the result is always a decimal ...
- even when the result is a whole number
- // division always results in 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 lower integer
>>> -4 // 2
-2
>>> -5 // 2
-3
Exponent Operator
Remainder Operator
- When we perform long division and divide one number by another ...
- we 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, when we divide by 2, the remainder is 0, the number is even
- If, when we divide by 2, the remainder is 1, the number is odd
Operator Precedence
- When more than one type of operator is used in a calculation ...
- the interpreter must decide which to use first
- The rules that are used to make this decision are called rules of
operator precedence
- The operator with the higher precedence is used first
- The precedence for Python's arithmetic operators is
| ** |
Exponentiation |
| *
/
//
%
|
Multiplication, division and remainder |
| +
-
|
Addition and subtraction |
Grouping with Parentheses
Expressions inside Expressions
Attendance
New Material
Breaking Long Statements into Multiple Lines
Whitespace Characters
- Not all characters appear as marks on a page
- The Python statement
print("Hello")
prints 5 characters
- But the statement
print("Hello world")
prints 11 characters, one of them a Space
- Space is a perfectly good character
- Even though it does not put a mark on the page
- Spaces are very important
- Canyoureadthisline?
- Not easily
- Spaces mark the end of one word and the beginning of the next
- Spaces are a relatively recent invention
- They first appeared in the Middle Ages
- The Space is a member of a special group of characters
whitespace
- These characters do not put a mark on the page
- But make the printed characters easier to read
- The other two whitespace characters are Tab and
newline
- The newline character moves the printed output down one line
- You type a newline by hitting Enter (PC) or Return (Mac)
Escape Sequences
- How do you add whitespace characters to a string
string literal
?
- With Space, you just hit the space bar on the keyboard
- There is a Tab key on your keyboard
- But when you use it inside a text editor ...
- different number of spaces are added ...
- depending on where you are in the line ...
- when you hit tab
- Here is what happens in
emacs ...
- when I type some characters ...
- hit the Tab then |
x |
xx |
xxx |
xxxx |
- Hitting Tab adds spaces ....
- to bring you to a tab stop ...
- which has a certain position on each line
- That is not the same thing as entering a Tab character ...
- which is a legitimate Unicode character
- And how are we to go down to the next line in a string literal?
- Just hitting the Enter or Return key does not work
>>> print("Line 1
File "<stdin>", line 1
print("Line 1
^
SyntaxError: EOL while scanning string literal)
- In Python and most computer languages ...
- we need a special way to write these characters inside a string literal
- The way we write the newline character is \n
- Like this
>>> print("Line 1\nLine 2\nLine 3")
Line 1
Line 2
Line 3
- This is an example of an
escape sequence
- An escape sequence is two characters you type ...
- to get one special character inside a Python string literal
- Escape sequences are used to represent characters ...
- that cannot be written any other way
- Escape sequences consist of the \ (backslash)
- Followed by one of these characters
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 |
- Why do we need the escape sequence \\?
- Unix uses a slash, /, to separate
directories ...
- in a
pathname
like /home/ghoffman/it116
- Windows uses \ for this purpose
- So a Windows pathname would be \home\ghoffman\it116
- To print a Windows pathname we need to use \\
>>> print("The path is C:\\temp\\data.")
The path is C:\temp\data.
- We can use the Tab escape character \t to space out
text on the screen
>>> print("Monday\tTuesday\tWednesday\tThursday\tFriday")
Monday Tuesday Wednesday Thursday Friday
- So that values in a table align properly
$ cat table.py
# prints a small table
print("Max\tMin")
print("-----------")
print("5\t1")
print("12\t2")
print("100\t0")
$ python3 table.py
Max Min
-----------
5 1
12 2
100 0
- The escape sequences for single and double quotes,
\' and \" ...
- are useful when writing a string literal with many quotes
>>> s = "He said \"It\'s me!"
>>> s
'He said "It\'s me!'
Concatenation Operator
Concatenating Strings with Numbers
- When you give the
print function a number ...
- it has to convert the number into a string in order to print it
>>> value = 5
>>> print("The value is", value)
The value is 5
- So printing a string and a number is no problem ...
- when they are separate arguments
- But you cannot concatenate a string and a number
- The + means addition when the first
value is an integer or a float ...
- but it means cocatenation when the first value is a string
- The values on both sides of a +
must both be numbers ...
- or both be strings
- You can't mix strings and numbers with
+
- If you do, you will get an error
>>> s = "The value is" + value
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
- Concatenation only works with strings
- So this works
>>> balance = "1000"
>>> s = "The balance is " + balance
>>> s
'The balance is 1000'
because balance is a string
- But this does not
>>> balance = 1000
>>> s = "The balance is " + balance
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
- In order to use a number in concatenation ...
- you have to convert it into a string
- You do this with the
str conversion function
>>> s = "The balance is " + str(balance))
>>> s
'The balance is 1000'
F-strings
- Often we want to print a string that contains the value of
variables
- For example, a script might want to print a greeting ...
- with the name of a person and their username ...
- using the variables name and
username
>>> name = "John Smith"
>>> username = "jsmith"
- What if I wanted to print the following string
Hello, John Smith! Your username is jsmith
- I could try
>>> print("Hello ", name, "! Your username is ", username)
Hello John Smith ! Your username is jsmith
- But the ! should not have a space before
it
- I could use concatenation
>>> print("Hello, " + name + "! Your username is", username)
Hello, John Smith! Your username is jsmith
- But that is a lot of work and is ugly
- However, since Python 3.6 I have another option
- I can use F-strings, formated strings
- An F-string begins with an f ...
- followed by a quoted string ...
- with the variables inside { } ...
- like this
>>> print(f"Hello, {name}! Your username is {username}")
Hello, John Smith! Your username is jsmith
- This is much easier to type ...
- and much less ugly
- But the real power of F-strings lies in what they can do with numbers
- To see the full power of F-strings go
here
Paths Through a Program
Control Structures
- When the interpreter runs a script it goes through the code statement by statement
- The order in which it executes the statements is call the
flow of control ...
- or the
path of execution
- In all the scripts you have seen so far the flow of control has been simple
- The interpreter starts at the top of the program ...
- executing each statement in turn ...
- until it reaches the bottom
- If this is all we could do with Python ...
- it would not be very useful
- To give programmers more options, Python has
control structures
- Control structures allow the interpreter to take different paths through the
code
Two Types of Control Structures
- There are two major types of control structures
- Conditional are like a fork in the road
- You come to a certain point and you have to decide which path to take
- If you take one path ...
- you do not take the others
- The diagram of a conditional looks something like this
- Loops allow you repeat a number of statements many times
- When diagrammed they look like this
- Both control structures are very useful ...
- and appear in most scripts
Class Exercise
Class Quiz