lec-15
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):
⦾ accumulator loops
⦾ string indexing & 2 new string operators
⦾ the for loop (with strings)
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....
| 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
| 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"
This is called (unsuprisingly) the
index operator
why yes, you DO have another type of bracket in your life now
| 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]) these shouldn't be too surprising
this seems reasonable
this is...uncommon
| s | t | r | i | n | g |
|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
|---|
s = "string"
s[1] = "p"
print(s)This is NOT a problem with the index operator - it's just that strings are immutable, which is fancytalk for unchangeable.
"fun" in "function"
True
"tio" in "function"
True
"joy" in "function"
False
returns
returns
returns
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.
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
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
collection_of_things = "abcdef"
for current_thing in collection_of_things:
# do something with thingAhhhh....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.
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.
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: