Input Validation¶

🖌 Dummy Variables¶

In [ ]:
for _ in range(5):
    print("Are we there yet?")

NOTES

  • Sometimes we need a variable that we don't actually use
    • The Python convention for such variables is to use only underscores: _, __, ___, etc.
    • Using a name like this communicates that the variable is completely ignored.
    • This comes up often when you want to use a for _ in range() loop to repeat the same thing over and over

🖌 Boolean Toggle¶

In [ ]:
is_green = True
for _ in range(10):
    if is_green:
        print("green!")
    else:
        print("red!")
    is_green = not is_green

NOTES

  • Discuss is_green = not is_green
  • Change is_green from False to True. Run it again.
  • Discuss other ways to accomplish alternating outcomes
    • for i in range(10): if i % 2 == 0...
    • the boolean toggle pattern can come in handy when you have a while loop and no variable keeping track of the iteration count
    • also useful when the toggle only happens under certain conditions

👩🏼‍🎨 ~Easy~ Dumb Game 😛¶

There are two players. Each takes a turn choosing an integer. The game ends when the sum of all numbers exceeds 100. The person with the highest individual sum wins.

easy_game.py¶

In [ ]:
def get_response(prompt):
    response = int(input(prompt))

def play_easy_game():
    is_first = True
    total = 0
    sum_a = 0
    sum_b = 0
    while total < 100:
        if is_first:
            response = get_response('Player 1: ')
            total += response
            sum_a += response
        else:
            response = get_response('Player 2: ')
            total += response
            sum_b += response
        is_first = not is_first
        
    if sum_a > sum_b:
        print('Player 1 wins!')
    else:
        print('Player 2 wins!')
        
play_easy_game()

🎨 abs¶

In [ ]:
abs(7-9)
In [ ]:
abs(9-7)

🖌 while and continue¶

In [ ]:
def get_number():
    while True:
        response = int(input('Enter a number less than 10: '))
        if response > 10:
            print('That was not less than 10. :P')
            continue
        return response

get_number()

NOTES

  • you can use continue with a while loop
  • Talk through the flow of execution

🧑🏽‍🎨 number_game.py¶

The inputs to the program are the lower bound, upper bound, and number of players.

The computer randomly picks a number between the lower bound and upper bound.

Each player is prompted to guess a number.

A guess is invalid if:

  • it isn't a positive integer
  • it isn't between the lower and upper bounds
  • another player has already guessed that number

If a player submits an invalid guess, they should be informed why their guess was invalid and they must guess again.

The player that is closest wins. Ties go to the player that guessed earlier.

NOTES

  • Draw it out: flowchart of program steps
    • setup game (pick random number)
    • get a guess for each player
    • determine the winner
  • get-a-guess
    • work with your neighbor: how would you design this?
    • what conditions must be tested? does the order matter?
    • how do you test that a number hasn't been guess before?
    • demonstrate while True + continue + return design
In [ ]:
import random


def is_integer(text):
    if not text:
        return False
    
    for c in text:
        if not c.isdigit():
            return False
    return True


def prompt_integer(prompt, lower, upper, invalid):
    while True:
        response = input(prompt)
        
        if not is_integer(response):
            print("Please enter a positive integer.")
            continue
            
        response = int(response)
        
        if response < lower or response > upper:
            print(f"The number must be between {lower} and {upper}.")
            continue
            
        if response in invalid:
            print("That number has already been guessed. Guess another.")
            continue
            
        return response
            

def find_winner(number, responses):
    winner_index = 0
    for index in range(1, len(responses)):
        if abs(responses[index]-number) < abs(responses[winner_index]-number):
            winner_index = index
    return winner_index


def play_number_game(lower, upper, num_players):
    number = random.randint(lower, upper)
    responses = []
    for player in range(num_players):
        response = prompt_integer(f'Player {player + 1} guess: ', lower, upper, responses)
        responses.append(response)
        
    print(f"The number is {number}")
    
    winner = find_winner(number, responses)
    print(f'Player {winner + 1} wins!')
        
        
# if __name__ == '__main__':
#     play_number_game(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))

play_number_game(1, 100, 5)

Key Ideas¶

  • Dummy variables
  • Boolean toggle
  • abs
  • while and continue
  • Input validation