In Class: Week 3 Tuesday
Run update21 to Create a grab this week's files:
$ update21
$ cd cs21/inclass
$ cd w03-boolean
$ pwd
/home/your_user_name/cs21/inclass/w03-boolean
$ ls
contains_a.py grade.py noWhammy.py tempConvert.py
Topics
- bool type and values True and False
- Conditional Statements
- Simple decisions with if statements
- Two-way decisions with if-else statements
- Multi-way decisions with if-elif-else statements
- Relational operators ==, !=, <, <e, >, >e
- Logical operators and, or, not
- Accumulation pattern with booleans using flag variables
We are going to do some of the following:
Conditional statements
- One example use of conditionals is a temperature converting app. It
would be wasteful to write two separate programs - one for converting
from Fahrenheit to Celsius and then another app from the opposite.
Let us use conditionals to combine the two together in tempConvert.py
- After learning about multi-way branching,
open up grade.py and try using a multi-way decision
statement (a series of if-elif statements) to convert a student's numeric
test score into a letter grade assuming a standard curve
- Next, we will combine accumulation patterns with boolean variables in
the program contains_a.py. We will write an algorithm that
checks to see if a work contains the letter 'a'. We will use a
boolean variable to assume there are no a's, and only change the value to
True if an 'a' is found. containsA is a flag variable
because it's value only changes to indicate a condition has been met at some
point. Once
its value has changed, it cannot go back. Here, once we find an 'a',
containA should never go back to being false.
- If you finish contains_a.py, try changing the algorithm so that
it takes if there is an 'a' OR an 'A'. Once that is
done, can we modify our algorithm to search if there is a second 'a'?
This requires us to store the index of the first 'a' and begin
the search anew but starting the for loop from the stored index.
-
Together, we will implement noWhammy.py. We'll ask the user
to enter numbers and check to see if they enter the whammy value (e.g., 0).
First, we'll use a boolean flag variable to see if they've entered the value
whammy value. Notice that the game continues even after hitting a whammy
since the for loop isn't finished. We'll add a break statement
to immediately stop the loop.