COMP1701-004
fall 2023
lec-15
Incoming!!!



about A3
about the midterm
We'll chat at the end of lecture.
from random import randint
DANGER_THRESHOLD = 2
STARTING_HP = 4
def lost_game(hit_points: int, cowardice_level: int) -> bool:
CRAVEN = 10
return dead(hit_points) or cowardice_level >= CRAVEN
def almost_dead(hit_points: int) -> bool:
return hit_points <= DANGER_THRESHOLD
def dead(hit_points: int) -> bool:
return hit_points <= 0
def damage() -> int:
return randint(1, 3)
def fight_should_stop(my_hp: int, enemy_hp: int) -> bool:
return dead(my_hp) or dead(enemy_hp) or not ok_to_fight(my_hp, enemy_hp)
def ok_to_fight(my_hp: int, enemy_hp: int) -> bool:
return not almost_dead(my_hp) or almost_dead(enemy_hp)
def fight_foe(my_hit_points: int) -> int:
enemy_hit_points = randint(1, 5)
print("Fighting a foe with", enemy_hit_points, "hp")
while not fight_should_stop(my_hit_points, enemy_hit_points):
my_hit_points -= damage()
enemy_hit_points -= damage()
print(f"Ow! {my_hit_points} left!")
return my_hit_points
def main() -> None:
my_hit_points = fight_foe(STARTING_HP)
print("I have " + str(my_hit_points) + " left.")
main()
Review Exercise
Show you know your terms by stating 15 facts about this source code, using these 15 terms (1 term per fact):
- argument
- block
- cast
- comparison operator
- compound boolean
- concatenation
- condition
- constant
- function body
- infinite loop
- logical operator
- LCV
- priming read
- sentinel loop
- string
RECALL

let's talk about these things today:
⦾ accumulator loops
⦾ string indexing & 2 new string operators
⦾ the for loop (with strings)
accumulator loops
For Your (Re)Consideration
We're back with the birdie from last lecture.
This time, let's imagine we're interested in how many times the bird's altitude goes OVER 10 metres.
As an example, if this is what's in the altimeter's memory...
0
15
4
11
10
0
-1altitudes >10
...then we'd want our program to return 2.
TASK
Write a program that counts how many time the altimeter readings go OVER 10 .
Assume you have a function called next_altitude() which gets the next altitude out of the altimeter's memory.
altitude = next_altitude()
curr_minute = 0
while altitude != -1:
print(f"{curr_minute}:{altitude}")
curr_minute += 1
altitude = next_altitude()Here's our code from last time.
Make the modifications needed to accomplish the task.
Hint: you'll need to bring in another variable and update it under certain conditions....

break and continue


string indexing & 2 new operators
NOT on midterm
string indexing & 2 new operators
| s | t | r | i | n | g |
|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
|---|
"string"
can be thought of as a sequence of characters, each in its own li'l box
each box gets its own li'l number, starting from 0
string indexing & 2 new operators
| s | t | r | i | n | g |
|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
|---|
computer folk (you're being indoctrinated as we speak) have a special name for these numbers: indexes
"index 0"
"index 3"
"index 5"
"t is at index 1"
"n is at index 4"
string indexing & 2 new operators
This is called (unsuprisingly) the
index operator
We can refer to "the character at index blahblahblah" with a new operator: [ ]
why yes, you DO have another type of bracket in your life now
string indexing & 2 new operators
| s | t | r | i | n | g |
|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
|---|
s = "string"
print(s[0])
print(s[4])
print(s[6])
print(s[-1]) Predict what the code will do
these shouldn't be too surprising
this seems reasonable
this is...uncommon
string indexing & 2 new operators
| s | t | r | i | n | g |
|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
|---|
s = "string"
s[1] = "p"
print(s)Predict what this code will do
This is NOT a problem with the index operator - it's just that strings are immutable, which is fancytalk for unchangeable.
string indexing & 2 new operators
Sometimes, you want to know whether a certain string is "inside" another string.
The in operator can tell you that.
"fun" in "function"
True
"tio" in "function"
True
"joy" in "function"
False
returns
returns
returns
string indexing & 2 new operators
Predict what this code will do
sentence = "My dog has fleas."
print("has" in sentence)
print("my" in sentence)
print(" " in sentence)
print("" in sentence)
print("g h" in sentence)
print(sentence[4] + sentence[8] + sentence[11])TASK
Make a function that takes in a string and returns how many vowels are in that string. Use a while loop.
You'll need an accumulator loop. And the index operator. And the in operator.

that thing we just did in the task - "walking through" a sequence of things, and doing something with each thing in that sequence - is SUPER COMMON in programming
the pattern that we saw has a lot of "noise" if we use a while loop
collection_of_things = "abcdef"
number_of_things = len(collection_of_things)
i = 0
while i < number_of_things:
current_thing = collection_of_things[i]
# do something with thing
i += 1
get upper bound
BTW
What category of loop is this?
initialize counter
grab next thing
bump up counter
many languages - including Python, Java, and C++ - provide a way to eliminate that noise
the for loop
the for loop
collection_of_things = "abcdef"
number_of_things = len(collection_of_things)
i = 0
while i < number_of_things:
current_thing = collection_of_things[i]
# do something with thing
i += 1
Using a while loop
collection_of_things = "abcdef"
for current_thing in collection_of_things:
# do something with thingUsing a for loop
Ahhhh....so quiet
Warning
It'll be confusing at first to have 2 different "in" floating around in your brain.
TASK
Redo our previous task with a for loop.
the for loop
the for loop
WARNING
Python's for loop is quite different from the for loops you will see in Java/C++ in 1502/1633.
When you start those courses, you might want to be preemptive and take a look at those languages' for loops so you're not feeling overly WTF during the course.
about the midterm
Midterm Specs
- 14 MCQ/TF
- 4 Trace (including 2"full" ones)
- 2 Coding
- pseudo => real (loop)
- solve => function, conditions
- 80 minutes
- yes to calculator
- yes to standard study sheet
- "you should..." docs have been updated
- I'll be releasing some practice question today, but....
Loop Trace
word = ""
num_letters = 0
num_words = 0
word = input("Next word? ")
while word != "DONE":
word = input("Next word? ")
num_letters += len(word)
num_words += 1
print("avg word length is", num_letters / num_words)
The code contains 2 errors. One is a logic error, the other is a possible runtime error. The errors appear on different lines.
Find each error, classify it, and provide an example input that would cause it to happen.
The purpose of this code is to get a sequence of words from the user, stop reading words when "DONE" is entered, and then report on the average word length of all the entered words:
lec-15
By Jordan Pratt
lec-15
accumulator loops | strings | indexing | for loops
- 275