IT 116: Introduction to Scripting
Class 9
Today's Topics
Tips and Examples
Review
New Material
Reading Assignment
You should read Chapter 5, Functions, from our
textbook, Starting Out with Python, before next week's class.
Homework 5
I have posted homework 5 here.
It is due this coming Sunday at 11:59 PM.
Quiz 2
I have posted the answers to Quiz 2 here.
Tips and Examples
Don't Use Whitespace at the Beginning of a Line
Setting Tab Length in nano
- One reason students sometimes use spaces to indent is that the default tab size
in
nano
is 8 spaces
- 8 is a lot of spaces
- But you can change the tab size in
nano
- To find out how, go
here
Converting Results to Integer
- Students often lose points on the homework assignments because they did not convert to integer correctly
- Converting to integer should be done by using the
round
function with only one argument
- There are two wrong ways to make a number an integer
- The first to use the integer devision operator, //
- When using this operator, the decimal part of the result is thrown away
- This makes the result less precise
- Calculating the Celsius temperature that corresponds to 30 degrees Fahrenheit
using normal division / gives us
>>> fahrenheit = 41
>>> (fahrenheit - 32) / 1.8
5.0
- If instead of using /
we use // we get
>>> fahrenheit = 41
>>> (fahrenheit - 32) // 1.8
4.0
- That value is way off
- Notice that even though we used // the result is a decimal
- When we do arithmetic on an integer and a float the result is always a float
>>> 4 // 2.0
2.0
>>> 4.0 // 2
2.0
- We only get an integer result if both operands are integers
>>> 4 // 2
2
- The second bad way to convert to an integer was to use the
int
conversion function
- This function also throws away the decimal part of a number
- If we use
int
we get
>>> fahrenheit = 35
>>> int((fahrenheit - 32) / 1.8)
1
- If we use
round
we get
>>>> round((fahrenheit - 32) / 1.8)
2
- Why the difference?
- Let's see what we get if we use neither function
>>> (fahrenheit - 32) / 1.8
1.6666666666666665
Use Spaces before and after =
Review
Logical Operators
Short-Circuit Evaluation
- Let's say you had a boolean expression like this
a > b and c > d
- If the first expression is false the result of the entire expression will be false
- Regardless of the whether the last expression is true or false
- Similarly, if we have the expression
a > b or c > d
and the first expression is true the result of the whole expression will be true
- Regardless of the whether the last expression is true or false
- It makes no sense for the interpreter to evaluate the last expression
- Because it cannot change the result
- When first operand determines the value
Python does not bother to evaluate the last operand
- This is called
short-circuit evaluation
- Another term for this feature is
lazy evaluation
Precedence of Logical Operators
- operator precedence
determines which operators are used before other operators
- The logical operators, and, or
and not have the lowest precedence
- Their precedence is lower than arithmetic operators
- And lower than the relational operators
** |
Exponentiation |
*
/
//
%
|
Multiplication, division and remainder |
+
-
|
Addition and subtraction |
>
<
>=
<=
==
!=
|
Relational Operators |
and
or
not
|
Logical per Operators |
Checking Numeric Ranges with Logical Operators
Boolean Variables
New Material
Loops
- One of the most important structures in all of programming is the loop
- The textbook calls loops repetition structures
- A loop repeats a group of statements under certain conditions
- Or a certain number of times
- Whenever you need to do something over and over you will use a loop
- There are two types of loops
- Loops controlled by counting
- Loops controlled by some condition
- In counting loops keep track of the number of times the loop is run
- And they stop when this loop count reaches a certain value
- Conditional loops will keep going as long as some condition is met
while
Loops
- A
while
loop keep repeating .as long as a certain condition is true
- It has the following format
while BOOLEAN_EXPRESSION:
STATEMENT
STATEMENT
...
- As long as the boolean expression is true the statements in the code block will be run
$ cat question.py
# keeps asking a question until it gets the right answer
reply = ''
while reply != 'yes' :
reply = input('Are we there yet? ')
print('Yeah!')
$ python3 question.py
Are we there yet? no
Are we there yet? no
Are we there yet? no
Are we there yet? yes
Yeah!
- We use a
while
loop whenever we do not know how many times the loop should run
- Let's say you wanted to add a series of numbers entered by the user
- You don't know how many numbers the user needs to add
- So your program can ask after each number entered whether there are more numbers
$ cat total.py
# add a series of numbers entered by the user
# demonstrates the use of a while loop
done = 'no'
total = 0
while done != 'yes':
number = int(input('Please enter a number: '))
total = total + number
done = input('If you are finished, enter "yes" ')
print('Your total is', total)
$ python3 total.py
Please enter a number: 4
If you are finished, enter "yes"
Please enter a number: 5
If you are finished, enter "yes"
Please enter a number: 6
If you are finished, enter "yes"
Please enter a number: 7
If you are finished, enter "yes"
Please enter a number: 8
If you are finished, enter "yes"
Please enter a number: 9
If you are finished, enter "yes"
Please enter a number: 10
If you are finished, enter "yes" yes
Your total is 49
- The condition in a
while
loop is evaluated before entering the loop
- This is why we give the variable done a value
before entering the loop
- Because a
while
loop test before looping, it is possible the loop will not be run
- In the code above, the loop would never be run
if we set the initial value of done to "yes"
- In other computer languages there are loops that test the condition
after the code block has been executed at least once
- But Python only has the
while
loop because it wants to be as simple as possible
Testing Variables in While Loops
- In the code above, I gave the variable done a value before the loop
- Here's the same script with that line removed
total = 0
while done != 'yes':
number = int(input('Please enter a number: '))
total = total + number
done = input('If you are finished, enter "yes" ')
print('Your total is', total)
- When I try to run this I get
$ python3 total_bad.py
Traceback (most recent call last):
File "total_bad.py", line 5, in <module>
while done != 'yes':
NameError: name 'done' is not defined
- done needs a value before entering the loop
- That value can be anything except "yes"
- If done is "yes" the loop will never run
done = 'yes'
total = 0
while done != 'yes':
number = int(input('Please enter a number: '))
total = total + number
done = input('If you are finished, enter "yes" ')
print('Your total is', total)
- When I run this I get
$ python3 total_stupid.py
Your total is
- Here we set the initial value of done to "yes"
- So boolean expression in the
while
loop is false
- And we never enter the loop
Infinite Loops
- When you write a
while
loop something must happen in the code loop
that will make the test become false
- Or the loop will go on forever
- Here is an example
>>> while True:
print("Are we there yet?")
Are we there yet?
Are we there yet?
Are we there yet?
Are we there yet?
Traceback (most recent call last):
^C File "<stdin>", line 2, in <module>
KeyboardInterrupt
- This is called an
infinite loop
- When your code goes into an infinite loop you have to abort the program
- You do this by hitting Control C
- The Control key on your keyboard is a modifier key like the Shift key
- It is used with another key and it changes what that other key means
- When we hold down the Control key and type another key
the combination has special meaning to a computer
- Control C tells a Unix machine to stop the program that is currently running
Data Validation
- The output of a program is only as good as its input
- If you give a program bad input data the output is worthless
- There is a saying in data processing
Garbage in
Garbage out
- This is sometimes abbreviated as "GIGO"
- A lot of data is entered by people, and people often make mistakes
- For example you might enter the value of a check you wrote and leave out the decimal point
- So instead of entering
$23.94
you enter
$2394
- Errors like this are hard for a program to spot because you might write a check for $2,394
- But it is often the case that valid data falls into a range
- For example a program calculating average rainfall knows that you can never have negative
inches of rain
- You could also set an upper limit, say to 50 inches
- You are unlikely to get that much rain at least around here
- The process of checking input to see that it is reasonable is called data validation
Data Validation Loops
while
loops are often used to validate user entered data
- Let's say we wanted the user to enter an integer greater than 0
- We would first ask the user for input
- Then test whether the value entered is greater than 0
- If not, we would print an error message and ask for new input
- This is an example of an
algorithm
- Which is a step-by-step description of how to perform a specific task
- A recipe is an example of an algorithm
- Here is one way of writing the algorithm above
get value from user
while value is not greater than 0:
print error message
get a new value from the user
- This is an example of pseudocode
- Pseudocode is a description of what the program will do
in language that mimics the structure of a computer program
- Here is the Python program that implements this algorithm
$ cat validation.py
# this program asks the user to enter an
# integer greater than 0 and keeps asking
# until it gets a proper value
# it is an example of using a while loop
# for data validation
value = int(input("Please enter an integer greater than 0: "))
while value <= 0:
print(value, "is less than 0")
value = int(input("Please enter an integer greater than 0: "))
print(value, "is greater than 0")
$ python3 validation.py
Please enter an integer greater than 0: -3
-3 is less than 0
Please enter an integer greater than 0: 0
0 is less than 0
Please enter an integer greater than 0: 5
5 is greater than 0
- Here we are assuming that the user has entered a string that can be turned into an integer
- In a real data validation situation we would test for this
- But that requires features of Python that we have not yet discussed
An Improved Data Validation Loop
- There is a problem with the code above
- The statement asking the user for input appears twice
- This violates the
DRY rule
- Don't Repeat Yourself
- Repeated code make a program longer
- It can also cause problems if you change one repeated statement but forget to fix the other
- We can get rid of the first
input
statement if we make sure the while loop always runs
- To to this we set a flag to
False
- And write the loop so it runs whenever the flag is not
True
- Inside the loop we ask the user for input and test it
- We set the flag to
True
if the input is good
- Here is the algorithm
set a flag to false
while the flag is not true
get input from the user and store in a variable
if the input value is good
set the flag to true
else:
print an error message
- Since this flag indicates where we are done why not call it done
- Here is code to implement the algorithm
done = False
while not done:
value = int(input("Please enter an integer greater than 0: "))
if value > 0:
done = True
else:
print(value, "is less than 0")
print(value, "is greater than 0")
- When we run this we get
$ python3 validation2.py
Please enter an integer greater than 0: -1
-1 is less than 0
Please enter an integer greater than 0: 0
0 is less than 0
Please enter an integer greater than 0: 5
5 is greater than 0
- Let's say that you were writing a program to compute the body mass index
- The body mass index tells you whether your weight is healthy or not
- There are two inputs
- If the height is measured in inches and the weight in pounds
the formula for calculating BMI is
bmi = weight / height ** 2 * 703
- We know a height cannot be 0
- The tallest man in the Guinness Book of Records was Robert Wadlow
- He measured 8 feet 11 inches or 107 inches
- The heaviest man weighed 975 pounds
- We can use these limits in a validation loop
- A validation loop must be a
while
loop
- Because the loop only stops when a correct value is entered
- Using these values we can write a BMI calculator that validates its input
$ cat bmi.py
# calculates the Body Mass Index using validation loops
done = False
while not done:
height = int(input("Please enter your height in inches: "))
if height <= 0 or height >= 107:
print("Height must be greater than 0 and less than or equal to 107")
else:
done = True
print()
done = False
while not done:
weight = int(input("Please enter your weight in pounds: "))
if weight <= 0 or weight >= 975:
print("Weight must be greater than 9 and less than or equal to 975")
else:
done = True
print()
bmi = weight / height ** 2 * 703
print("Your Body Mass Index is", round(bmi))
bmi = weight / height ** 2 * 703
print("Your Body Mass Index is", round(bmi))
$ python3 bmi.py
Please enter your height in inches: 0
Height must be greater than 0 and less than or equal to 107
Please enter your height in inches: 200
Height must be greater than 0 and less than or equal to 107
Please enter your height in inches: 60
Please enter your weight in pounds: 1000
Weight must be greater than 9 and less than or equal to 975
Please enter your weight in pounds: 0
Weight must be greater than 9 and less than or equal to 975
Please enter your weight in pounds: 150
Your Body Mass Index is 29
- Notice that if the user enters a reasonable value the block of the loop is never executed
Compound Statements
Recursion
Attendance
Graded Quiz