Lab 6: Notes

Hints on Lab 6

  1. Choosing a random element

    When choosing a random element from a sequence, use the choice function, in the random module. If you use randint be careful about off-by-one issues with randint and indexing. Recall that randint has an inclusive end, thus list[randint(0, len(list))] could potentially index past the end of the list (in randint returns len(list)). In this case you want to substract one from the upper bound, i.e., list[randint(0, len(list)-1)]. Using choice would be better.

  2. Handling invalid input

    If you decide to tackle checking user input for validity, it’s a good practice to obtain valid input before proceeding onto other parts of the game/problem. Think of these as two separate sections of your loop. There is a section of your program that obtains a valid input. Once you are past that code, all input is guaranteed to be valid and thus subsequent sections do not need to check for/worry about validity.

    If we don’t want to proceed until we have a valid input from the user, we may not know how many times we will need to prompt the user before they provide that valid input.

    Thus a common pattern is to use a while loop, e.g.:

     user_input = input(...)
     while is_invalid(user_input):
         user_input = input(...)
    

    Solutions with just an if statement will only work for one invalid input, not many. If you find yourself writing nested if statements, or multiple loops, pause and think through the problem a bit more. Such complicated structures are rarely needed.

    Be careful not to integrate invalid input alongside valid input such that a repeated input prompts printing the entire game summary again. As always, pay close attention to the specification.