In Class: Week 3 Tuesday
Run update21 to Create a week03 subdirectory in your cs21/class
directory:
% update21
% cd
% cd cs21/class
% cd week03
% pwd
/home/your_user_name/cs21/class/week03
% ls
Topics
- Accumulation pattern with strings
- bool type and values True and False
- Conditional Statements
- Simple decisions with if statements
- Two-way decisions with if-else statements
- Multi-way decsions with if-elif-else statements
- Relational operators ==, !=, <, <e, >, >e
- Logical operators and, or, not
- Accumulation pattern with booleans using flag variables
- Random library
We are going to do some of the following:
Accumulating Strings
- open drop_letter.py in vim:
together we will write a program that takes an input string and
creates a new string that consists of every other character dropped
from the first string. This is an example of using the accumulator
pattern to accumulate a string value.
Conditional statements
- Open is_odd.py. Together, we'll use an if-statement to
determine if a number is odd or not.
- Now, 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. 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.
Random library
- Open up coinFlip.py. Write a program that flips a virtual coin
by using the choice() method from the random library. Flip a coin
10 times and use an accumulator pattern to count how many times the coin came
up heads. Once that is done, add a second accumulator pattern to store the
sequence of coin flips. We'll represent a heads as "H" and tails
as "T"
Pattern of stars
- In stars.py we'll closely inspect the relationship between
the loop variable and the inner-loop body by printing out several
different patterns of stars and other characters