IT 116: Introduction to Scripting
Class 8
Tips and Examples
Review
New Material
Studying
Microphone
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.
Questions
Are there any questions before I begin?
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
- 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
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
Control Structures
- Python, like most computer languages, has control structures
- Control structures allow the interpreter to take different paths through the
code ...
- depending on certain conditions
- The order in which the statements of a script are executed is called
path of execution
...
- or the flow of control
- Without control structures programs could not do much
- They could only start at the top of the scripts
- And proceed line by line to the bottom
Two Types of Control Structures
- There are two major types of control structure
- 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
- Loops allow you repeat a number of statements many times
- Both are very useful ...
- and appear in most scripts
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
- 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
relationship
- 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
- Both an
if
statement and and if
-else
statement must be indented properly ...
- or they will not work
- All the statements in a code block must indented the same ..
- using the same characters
- It is best to indent with a Tab character
Comparing Strings
Nested if
Statements
Testing a Series of Conditions
- Sometimes you have test more than one condition
- A program to turn scores into a letter grade is one example
- Here is one such program
$ 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
- Let's say you 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 more efficient
- But it can be helpful to a programmer under certain situations
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
- Boolean variables are often used as
flags
- A flag represents a certain condition in a program
- Flags can make a program much more readable
- For example a program to compute the price of a ticket might look like this
if age < 18:
minor = True
else:
minor = False
if age >= 65:
senior = True
else:
senior = False
- You could then use the flags minor and
senior
later in the program
- Actually there is a shorter way to achieve the same results
minor = age < 18
senior = age >= 65
- The expressions on the right are both boolean expressions
- Normally you would set a flag if you wanted to check a condition more than once
- But even if you only use the value of a flag once it will 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")
- If you think about it, 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 the variable 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
Studying
Class Exercise
Class Quiz