CS 111 w20 lecture 12 outline

1 Practice

  • poll: infinite while loop (no increment)
  • translate this for loop into a while loop:
total = 0
for i in range(10):
    total += i
print(total)
total = 0
i = 0
while i < 10:
    total += i
    i += 1
print(total)

2 Return to the guessing game

Generate a random secret number, have the player try and guess it

2.1 Validate input

guess = input("Guess a number ")
while not guess.isdecimal() or int(guess) < 0 or int(guess) > 100:
    guess = input("Guess a number ")
guess = int(guess)

2.2 Game loop

import random

def get_guess():
    guess = input("Guess a number ")
    while not guess.isdecimal() or int(guess) < 0 or int(guess) > 100:
        guess = input("Guess a number ")
    guess = int(guess)
    return guess


secret_num = random.randint(0, 100)
tries = 10
guess = get_guess()
while tries > 0 and guess != secret_num:
    tries -= 1
    diff = secret_num - guess
    diff = abs(diff)
    if guess != secret_num:
        if diff <= 5:
            print("lava")
        elif diff <= 10:
            print("warm")
        else:
            print("cold")
        guess = get_guess()
if guess == secret_num:
    print("YOU GOT IT!!!")
else:
    print("Better luck next time. The number was", secret_num)

3 Review

3.1 is_valid_variable_name

I'm trying to write a function that takes a string and returns whether that string would be a valid variable name. Remember that a variable name can only have numbers, letters, and underscores. In addition, a variable name cannot start with a number. Describe why each of the versions below will not return the correct result.

def is_valid_variable_name1(name):
    if name[0].isdecimal():
        return False
    for c in name:
        if c.isalnum() or c == "_":
            return True
        else:
            return False

def is_valid_variable_name2(name):
    ok_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
    return name[0] in ok_characters and name in ok_characters

def is_valid_variable_name3(name):
    result = True
    for c in name:
        result = c.isalnum()
        result = c == "_"
    return result and name[0].isdecimal()

3.2 List Mystery

What will be printed by the following code?

v = [4, 5, 6, 7, 8, 9]
v[0] = v[-1] - v[-2]
print(v)
i = v[0] + 2
v[i] = v[i - 2] - v[i - 3]
print(v)
v[len(v) - 2] = i * 2
print(v)