Lab 2 - if/elif/else; in list; loop

Directions for Labs


  • Submit your completed lab file online to CourSys (not Canvas). Labs are marked on completion, not correctness, so complete each part to the best of your ability and learn!
  • It is recommended that students attend in-person lab sections for lots of help!
    • If you would like to attend an in-person lab section, you are welcome to come to any (or more than one) lab section.
    • There is no need to attend the section you are enrolled in.
    • There is no need to attend any lab sections: there is no attendance taken.
    • You can complete the lab on your own time or own computer if you like.
  • While completing these labs, you are encouraged to help your classmates and receive as much help as you like. Assignments, however, are individual work and you must not work with another person on assignments.

Yes/no/maybe: if/elif/else


  1. Inside your cmpt120 folder, create a new folder for lab2 and make a lab2.py file.
    • See lab 1 for more detailed directions.
  2. Ask the user a yes/no/maybe question about if they like something.
    • Use an input() statement along with a prompt.
    • Your prompt might look like:
      "Do you like _________? (yes/no/maybe) "
  3. Handle each of "yes", "no", and "maybe" by printing different reactions.
    • Use an if statement to check for "yes". If yes print an enthusiastic message like "GREAT!".
    • Add an elif statement to check for "no". If no, print a sad message, like "Oh no!".
    • Add another elif statement to check for "maybe". If maybe, print any message you like.
    • If the input was not one of the above, then print a message like "I don't understand".
    • Hint: See notes in section 2.2 for an example on using if/elif/else.
  4. Experiment and answer:
    What happens if you change your first elif into just an if? What goes wrong?
    • Experiment with your code and try it.
    • Add a comment to your lab to explain what goes wrong.
    • Hint: Look at how it works with the else.

True Boolean Expressions in if


This section experiments with a few interesting True/False cases for if statements. The coding is simple, but understanding it is more important!

  1. Copy the following code into your lab file:
        name = "Brian"
        if name == "Brian":
            print("Hello wonderful person!")
        else:
            print("I bet you're nice too!")
    • Change both hard-coded strings to be your name!
  2. Run the code
    • Notice how the if statement will always be true, and execute the "Hello..." printing statement.
    • This is perhaps not surprising, but it sets us up to understand the next cases.
  3. Copy the following code into your lab file:
    if True:
        print("Always true")
    else:
        print("Will never see this") 
    • Run the code.
    • Notice that this if statement is also always true, and always prints "Always true".
    • Notice what VS Code does to the code to show it understands how it's always True?
  4. Try changing the True to False and experiment with the code.
    • Notice VS Code grays out the first print() statement because it knows it will never be executed.
  5. Copy the following code into your lab file:
    if "Hi":
        print("Weird, eh?")
    else:
        print("Will never see this")
    • Run it. What do you see?
    • In Python, any non-empty string is True. Therefore this code will always print "Weird, eh?"
  6. Copy the following code into your lab file:
    if name == "Waldo" or "Cookie Monster":
        print("My heros!")
    • Run it. What does it print?
    • In your lab file, add a comment to state what is printed, and explain why.
    • How should this if statement be fixed to check if the name is either "Waldo" or "Cookie Monster"? Fix the code now and test it (you likely want to hard-code different values for name to test).

Guess my songs: in List

  1. Create a list of the names of three of your favourite songs:
    • List your songs in all upper case.
    • Recall that a list looks like:
      colours = ["RED", "GREEN", "BLUE"]
    • Hint: Create a variable name favourite_songs (or a similar name).
    • Hint: Change the list to store the names of your favourite songs. Make the names all caps (for later use with upper()).
  2. Ask the user to enter a song name as a guess.
    • Hint: Use input(), and store the result in a well-named variable.
  3. Make the user's input all capitals.
    • Hint: Use upper().
    • Hint: You can chain together functions.
    • Hint: Your code may look like:
      guess = input("...").upper()
  4. Print out the user's guess so you can see what is in your variable (helps for debugging!)
  5. Make the code ignore spaces and periods at the start/end of the guess.
    • Hint: Add to the input("...").upper() chain above.
    • Hint: You want to add a strip().
    • Hint: Try strip(" .") to get rid of spaces and periods.
    • Test it!
  6. Check if the user's guess is one of your favourites. Print a message letting them know either way.
    • Hint: use in to see if the guess is in your favourites list.
    • Hint: Structure might look like if ____ in _____:...
    • Hint: Full code might be:
      if guess in favourite_songs:
          print("I love that song!")
      else:
          print("Not that one!")

Guess: Loop


Finally, let's allow the user a few guesses!

  1. Change your code above to give the user four chances to guess your songs:
    • Decide what will happen before the loop, and what will happen inside the loop.
    • Hint: You want to repeatedly execute a few lines of code, so use a for loop.
    • Hint: Your for loop statement is likely: for i in range(4):
    • Hint: Before the loop you should create your list of favourites.
    • Hint: Inside the loop you should ask the user for a guess (input()) and check their guess (if...).
    • Hint: Remember that to put statements inside the loop you'll need to indent them one extra time.
  2. Run your code and test it.
  3. If stuck, here's the likely layout of your code:
    favourite_songs = [...]
    for i in range(4):
        guess = ...
        print("You guessed "+ ...)
        if guess in favourite_songs:
            ...
        else:
            ...

Submission


Submit your lab2.py file to CourSys by Sunday midnight. Remember you can submit up to 3 days late with no penalty if needed (but please plan to get it done on time to stay up to date on the course!)

Topics Covered

  • if/elif/else
  • true/false and "XYZ" is true
  • input in list; upper(), strip()
  • Looping through N times