IT 116: Introduction to Scripting
Class 8
General Advice
Tips and Examples
Review
New Material
Microphone
Questions
Are there any questions before I begin?
Homework 4
I have posted homework 4 here.
It is due this coming Sunday at 11:59 PM.
Quiz 2
I have posted the answers to Quiz 2
here.
Today's Class
Todays I will discuss logical operators and boolean variables.
General Advice
Keep Each Study Period Short
- Do not spend more than 1 hour on a study session
- Otherwise you may find that your attention wanders ...
- as your brain gets tired
- If you spread out your study session over the week ...
- you will learn more
- The first time you read something new you might miss important details
- Your brain needs time to absorb the material you have just studied
- Each time you look at new material it will become more familiar
- Things that you did not understand at first become clearer with time
- It's also a great way to break up a big task ...
- into smaller chunks
- A few summers ago I needed to spread mulch over my yard
- My house is on a corner so it's a big yard
- It took 170 bags of mulch to cover the area
- I no longer have the stamina that I had when I was your age
- I could not spread 170 bags in one, two or even three sessions
- But I learned that I could spread 6 bags without to much trouble
- Every day when the weather permitted I spread 6 bags
- By the end of the summer the job was done
Tips and Examples
Use Tabs in a Code Block
- A code block is a group of statements ...
- that are only executed under certain conditions
- All
control structures
use code blocks
- In Python, all statements in a code block are indented the same amount
- There are two ways to indent a code block
- You a free to use either one
- But you cannot mix tabs and spaces within a code block
- If you do you will get an IndentationError
- Why?
- Because the Python interpreter checks each line in a code block
- It wants to see some
whitespace
characters at the start of the line
- If it does, it goes on to the next line ...
- where it expects to see the same whitespace characters
- If you mix tabs and spaces, it may look OK to you
- But Tab and Space are different characters ...
- because they have different Unicode numbers
- To prevent indentation errors, follow a simple rule
- Always use Tabs to indent code blocks
- Look at the following code
num = int(input("Number: "))
if num % 2 == 0:
print(num)
print('This number is even')
- It looks fine but when I run it I get
$ python3 indent_test.py
File "indent_test.py", line 5
print('This number is even')
^
IndentationError: unindent does not match any outer indentation level
- It looks like the both lines are indented the same amount
- But that is not what the interpreter thinks
- I used 4 Spaces to indent the first line in the code block
- But I used one Tab in the second
- This is the kind of error that can drive you crazy
- Because the indentation looks good to our eyes
- To avoid this problem you need to be consistent
- You can indent with one Tab character
- Or you can indent with many spaces
- It is simpler to use Tabs
Misleading Error Messages
- If your code violates the rules of Python ...
- you will get an error message
- Errors of this type are called
syntax errors
- The interpreter is good at spotting these errors
- But it isn't always good at telling you where the problem is
- The most important thing an error message tells you ...
- is that your code does not work
- Interpreters run through your code expecting certain things
- When the interpreter sees a " at the beginning of a
string literal
...
- it expects to see another " at the end
- When the interpreter sees a ( ...
- it expects a following )
- If it does not see the character on one line, it looks at the next
- This means that the error message sometimes give you the wrong line number
- The error occurs on one line where you are missing a
" or )
- But the interpreter does not realize it until it gets to a following line
- Here is an example from a student's homework script
- When I ran the code I got the following
$ python3 hw4.py
File "hw4.py", line 4
print("Your score is ", score)
^
- Line 4 of the code was
print("Your score is ", score)
- There is nothing wrong with this line
- But there is with the line above it
score = int(input("What is your score? ")
- If you look carefully you will see that there are two left parentheses,
( ...
- but only one right parenthesis, )
- If you can't see the error on one line ...
- look at the line above
- Unclosed parentheses are often a problem
- For every ( there should be a
)
- There is a trick for spotting this
- You count the number of parentheses in a special way
- Start with 0
- Every time you come across a ( add 1
- Every time you come across a ) subtract 1
- Should should end up with 0
Review
if Statements
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
can only be True or False
- There are two boolean
literals
- Notice the capitalization
True not true
False not false
- The function
bool will covert its argument to a boolean value
- It will convert any number that is not 0 to
True
- It will convert the empty string to
False
- And any other string to
True
Relational Operators
- Boolean expressions are often created using
relational operators
- Relational operators compare two values ...
- and return
True or False depending on their
relative values
- 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 that you will probably make many times
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 |
if-else Statements
Indentation in the if-else Statement
- The
keywords
if and else
must be the same distance from the left margin
- or you will get an indentation error
- All the statements in a code block must indented the same amount ...
- using the same characters ...
- or you will get an error
- It is best to indent with a Tab character
Comparing Strings
Nested if Statements
Testing a Series of Conditions
- Sometimes you have to test more than one condition
- A program to turn scores into a letter grade is one example
- This can be done with a nested
if statement ...
- like this
$ cat grade.py
# this programs turns a score into a letter grade
# it demonstrates using nested if statements
# 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
- Python has a different kind of
if statement for these
situations
- It is the
if-elif-else statement
- It has this format
if BOOLEAN_EXPRESSION_1:
STATEMENT
...
elif BOOLEAN_EXPRESSION_2:
STATEMENT
...
elif BOOLEAN_EXPRESSION_3
STATEMENT
...
...
[else:
STATEMENT
...]
- The [ ] around the
else clause
indicates that it is optional
- The keyword
elif is short for "else if"
- Notice that all the conditions line up vertically
- This 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
Attendance
New Material
Logical Operators
Short-Circuit Evaluation
- There are some features of all computer languages ...
- that are only noticeable in special situations
- Here is one example
- Let's say your code has the boolean expression
a > b and c > d
- And say the a is not greater than
b
- Then the entire expression will be
False ...
- even if c is greater than d
- Because both operands must be
True for and
to return True
- Similarly, if we have the expression
a > b or c > d
- And a is greater than
b ...
or will return True ...
- no matter what the relationship between c and
d
- Because only one operand needs to be
True for or
to return True
- In both cases the second operand cannot change the result
- So Python will not evaluate the second expression ...
- because it cannot change the result
- This is called
short-circuit evaluation
- Also know as
lazy evaluation
- This makes the interpreter slightly faster ...
- because it does not have to evaluate the 2nd expression
- But it can be helpful to a programmer under certain situations ...
- because it makes the code shorter
Checking Numeric Ranges with Logical Operators
Precedence of Logical Operators
- When we write an expression like
a + b > c and c * d < a
there are three different kind of operators
- Arithmetic - +,
*
- Relational - >,
<
- Logical - and
- operator precedence
determines which operators are used first
- The logical operators are and,
or and not
- They 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
Boolean Variables
- A variable is a place in memory with a name ...
- that holds a single value
- If the value a variable holds is
True or False ...
- it is a boolean variable
- Sometimes there is a certain condition ...
- which effects the rest of the program
- It's best to test for that value early in the code ...
- and store it in a boolean variable
- Boolean variables used this way are called
flags
- Consider the following example
- Movie theatres have three different price ranges
- This information could be store in two flags
- The following code will set the flags
if age < 18:
minor = True
else:
minor = False
if age >= 65:
senior = True
else:
senior = False
- Actually there is a shorter way to achieve the same results
minor = age < 18
senior = age >= 65
- Flags can make the code more readable
- Compare these two versions of the a script that calculates ticket prices
$ cat tickets_1.py
# this program calculates ticket prices
age = int(input("What is your age? "))
if age < 18:
print("Your ticket will cost $10")
elif age >= 65:
print("Your ticket will cost $15")
else:
print("Your ticket will cost $25")
$ cat tickets_2.py
# this program calculates ticket prices
age = int(input("What is your age? "))
minor = age < 18
senior = age >= 65
if minor:
print("Your ticket will cost $10")
elif senior:
print("Your ticket will cost $15")
else:
print("Your ticket will cost $25")
Keep Your Code Short
- One of the rules of good writing is that shorter is better than
longer
- That's because a reader's attention is not infinite
- People will only pay attention for so long ...
- before turning away
- The same is true with code
- Look at the ticket script above
- Notice that each
if clause has the string "Your ticket will cost"
if minor:
print("Your ticket will cost $10")
elif senior:
print("Your ticket will cost $15")
else:
print("Your ticket will cost $25")
- The real work of the
if statement
is to set ticket price
- Printing the message is a different task
- We can make the code shorter by setting the variable
price ...
- inside an
if-elif-else statement ...
- then using price in a single
print statement
age = int(input("What is your age? "))
minor = age < 18
senior = age >= 65
if minor:
price = 10
elif senior:
price = 15
else:
price = 25
print("Your ticket will cost $" + str(price))
- Why did I use
concatenation
in the
print statement ...
- instead of giving
print two arguments?
- With two arguments there would have been a space in the output
- It would appear between $ and the price
- like this
Your ticket will cost $ 25
Class Exercise
Class Quiz