IT 116: Introduction to Scripting
Class 9
Tips and Examples
Review
New Material
Microphone
Graded Quiz
You can connect to Gradescope to take weekly graded quiz
today during the last 15 minutes of the class.
Once you start the quiz you have 15 minutes to finish it.
You can only take this quiz today.
There is not makeup for the weekly quiz because Gradescope does not permit it.
Readings
If you have the textbook you should read Chapter 4,
Repetition Structures, from
Starting Out with Python.
Solution to Homework 3
I have posted a solution to homework 3
here.
Let's take a look.
Homework 5
I have posted homework 5 here.
It is due this coming Sunday at 11:59 PM.
Questions
Are there any questions before I begin?
Tips and Examples
- All scripts for this course must have a script comment at the
top of the script
- The comment should describe what the script does
- I does not need to be longer than a single sentence
- You don't need a comment on every line
- That can actually make the script harder to read
- Later on in the course you will learn how to write functions
- Each function will need its own comment ...
- that describes what the script does
Don't Use Whitespace at the Beginning of a Line
Converting Results to Integer
- Students sometimes 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
- We can see this when doing calculation using /
and //
- Let's convert Fahrenheit to Celsius using regular division
>>> 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 ...
- because integer division throws away the decimal
part
- The second wrong way to convert to an integer ...
- is 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
- 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 the first operand determines the value of the whole expression ...
- Python does not bother to evaluate the last operand
- This is called
short-circuit evaluation
- Another term for this is
lazy evaluation
Precedence of Logical Operators
- Operator precedence
determines which operators are evaluated first
- 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 |
not |
Logical NOT |
and |
Logical AND |
or |
Logical OR |
Checking Numeric Ranges with Logical Operators
- A program should always check that input values make sense ...
- before using them in a calculation
- This is called
data validation
- Say you are writing a program to calculate retirement benefits
- You need to ask the user for their age
- But the age needs to be in a certain range
- Your program should not accept age values of 1 or 200
- We might want to make sure that the values were between 16 and 65
- When we need to determine whether a value is inside a range ...
- we use the
and
operator
age >= 16 and age <= 65:
- If we wanted to determine whether a value is outside a range ...
- we use the
or
operator
age < 16 or age > 65:
Boolean Variables
Attendance
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 should use a loop
- There are two types of loops
- Loops controlled by some condition
- Loops controlled by counting
- Conditional loops will keep going as long as some condition is met
- Counting loops keep track of the number of times the loop is run
- They stop when this loop count reaches a certain value
while
Loops
- In Python there is only one conditional loop, the
while
loop
- A
while
loop keeps repeating as long as a certain condition is
True
- It has the following format
while BOOLEAN_EXPRESSION:
STATEMENT
STATEMENT
...
- A while loop stops when the condition becomes
False
$ 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!
- The text marked in blue is entered by
the user
- Whenever you do not know how long a loop should run ...
- you should use a
while
loop
- 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 after each number is entered ...
- you ask the user if they are done
- There are much better ways to do this ...
- but this code shows how a
while
loop works
$ 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: yes
Your total is 15
- The text marked in blue is entered by
the user
- 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
- The loop would never be run if we set done
to "yes"
- In other computer languages there are other conditional loops
- For example loops that test the condition ...
- after the code block has been executed once
- But Python only has the
while
loop ...
- because it wants to be as simple as possible ...
- and the other conditional loops are not strictly necessary
- There is nothing these other loops can do ...
- that Python can't do with the
while loop
Testing Variables in While Loops
- What would happen if I did not give done a
value ...
- before entering the loop?
- Here is the altered code
$ cat total_bad.py
# tries to add a series of numbers entered by the user
# but cannot enter the loop because done is improperly initialized
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)
- And this is what happens when I run it
$ 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
$ cat total_stupid.py
# tries to add a series of numbers entered by the user
# but can't because done is given the wrong initial value
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 0
- 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
- A
while
loop stops when its condition becomes False
- The boolean expression in the
while
header has to be True
...
- when the loop starts ...
- or the code block would never execute
- But the code block must change something to make this expression
False
...
- or the loop will go on forever
- Here is an example
>>> done = False
>>> while not done:
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
- The code block does nothing to change the value of done ...
- so the loop will go on forever ...
- unless I do something to stop it
- This situation 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
- It also works on the Windows command line ...
- and when running a script in IDLE
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
- Think of a program that calculates average rainfall
- 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
- Checking input to see that it is reasonable is called data validation
Data Validation Loops
while
loops are often used to check values entered by the user
- 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
- An algorithm 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 not greater 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 not greater than 0
Please enter an integer greater than 0: 0
0 is not greater 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 makes a program longer
- It can also cause problems if you change one repeated statement ...
- but forget to change the other
- We can get rid of the first
input
statement ...
- if we make sure the code will enter the
while
loop
- We can do this by setting a flag to
False
- And change the loop condition so it runs if 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
- The flag tells the loop when we are done
- So a good name for it is 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 not greater 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 not greater than 0
Please enter an integer greater than 0: 0
0 is not greater 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 loops
- 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
- If the user enters a value that is in the proper range
- The code never enters the
while
loop
Using a while
Loop to Add Numbers
- Consider the problem of adding positive integers
- Positive integers are all the integers greater than 0
- When adding numbers entered by a user ...
- we have to know when to stop
- Earlier in this class I did this in a clumsy way
- After each number I asked the user it they were done
- But there is another approach
- We only want to add positive integers
- If the user enters 0 or a negative number ...
- we can use that as a signal to stop adding ...
- and print the results
- To prevent having to use two
input
statements ...
- we will set the flag done to
False
...
- then keep looping until done is no longer
False
- Here is the code
# script to add positive integers using a while loop
done = False
total = 0
while not done:
num = int(input("Number: "))
if num > 0:
total = total + num
else:
done = True
print("Total", total)
- When we run the script we get
$ python3 while_add.py
Number: 45
Number: 84
Number: 92
Number: 5
Number: 0
Total 226
- Againg the numbers in blue are entered
by the user
Compound Statements
Class Exercise
Class Quiz