Class Coding Lab: Conditionals

The goals of this lab are to help you to understand:

  • Relational and Logical Operators
  • Boolean Expressions
  • The if statement
  • Try / Except statement
  • How to create a program from a complex idea.

Understanding Conditionals

Conditional statements permit the non-linear execution of code. Take the following example, which detects whether the input integer is odd or even:


In [ ]:
number = int(input("Enter an integer: "))
if number %2==0:
    print("%d is even" % (number))
else:
    print("%d is odd" % (number))

Make sure to run the cell more than once, inputting both odd and even integers to try it out. After all, we don't know if the code really works until we test out both options!

On line 2, you see number %2 == 0 this is a Boolean expression at the center of the logic of this program. The expression says number when divided by 2 has a reminder (%) equal to (==) zero. The key to deciphering this is knowing how the % and == operators work. Understanding the basics, such as these, areessential to problem solving with programming, for once you understand the basics programming becomes an exercise in assembling them together into a workable solution.

The if statement evaluates this Boolean expression and when the expression is True, Python executes all of the code indented underneath the if. In the event the Boolean expression is False, Python executes the code indented under the else.

Now Try It

Write a similar program to input an integer and print "Zero or Positive" when the number is greater than or equal to zero, and "Negative" otherwise.

To accomplish this you must write a Boolean expression for number greater than or equal to zero, which is left up to the reader.


In [ ]:
# TODO write your program here:

Rock, Paper Scissors

In this part of the lab we'll build out a game of Rock, Paper, Scissors. If you're not familiar with the game, I suggest reading this: https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissor Knowledge of the game will help you understand the lab much better.

The objective of the lab is to teach you how to use conditionals but also get you thinking of how to solve problems with programming. We've said before its non-linear, with several attempts before you reach the final solution. You'll experience this first-hand in this lab as we figure things out one piece at a time and add them to our program.


In [ ]:
## Here's our initial To-Do list, we've still got lots to figure out.
# 1. computer opponent selects one of "rock", "paper" or "scissors" at random
# 2. you input one of "rock", "paper" or "scissors"
# 3. play the game and determine a winnner... (not sure how to do this yet.)

Randomizing the Computer's Selection

Let's start by coding the TO-DO list. First we need to make the computer select from "rock", "paper" or "scissors" at random.

To accomplish this, we need to use python's random library, which is documented here: https://docs.python.org/3/library/random.html It would appear we need to use the choice() function, which takes a sequence of choices and returns one at random. Let's try it out.


In [ ]:
import random
choices = ['rock','paper','scissors']
computer = random.choice(choices)
computer

Run the cell a couple of times. It should make a random selection from choices each time you run it.

How did I figure this out? Well I started with a web search and then narrowed it down from the Python documentation. You're not there yet, but at some point in the course you will be. When you get there you will be able to teach yourself just about anything!

Getting input and guarding against stupidity

With step one out of the way, its time to move on to step 2. Getting input from the user.


In [ ]:
# 1. computer opponent select one of "rock", "paper" or "scissors" at random
import random
choices = ['rock','paper','scissors']
computer = random.choice(choices)

# 2. you input one of "rock", "paper" or "scissors"
you = input("Enter your choice: rock, paper, or scissors: ")
print("You chose %s and the computer chose %s" % (you,computer))

This is taking shape, but if you re-run the example and enter pizza you'll notice a problem.

We should guard against the situation when someone enters something other than 'rock', 'paper' or 'scissors' This is where our first conditional comes in to play.

In operator

The in operator returns a Boolean based on whether a value is in a list of values. Let's try it:


In [ ]:
# TODO Try these:
'rock' in choices, 'mike' in choices

You Do It!

Now modify the code below to only print your and the computer's selections when your input is one of the valid choices. Replace TODO on line 8 with a correct Boolean expression to verify what you entered is one of the valid choices.


In [ ]:
# 1. computer opponent select one of "rock", "paper" or "scissors" at random
import random
choices = ['rock','paper','scissors']
computer = random.choice(choices)

# 2. you input one of "rock", "paper" or "scissors"
you = input("Enter your choice: rock, paper, or scissors: ")
if (TODO):  # replace TODO on this line
    print("You chose %s and the computer chose %s" % (you,computer))
    # 3. play the game and determine a winnner... (not sure how to do this yet.)
else: 
    print("You didn't enter 'rock', 'paper' or 'scissors'!!!")

Playing the game

With the input figured out, it's time to work on the final step, playing the game. The game itself has some simple rules:

  • rock beats scissors (rock smashes scissors)
  • scissors beats paper (scissors cut paper)
  • paper beats rock (paper covers rock)

So for example:

  • If you choose rock and the computer chooses paper, you lose because paper covers rock.
  • Likewise if you select rock and the computer choose scissors, you win because rock smashes scissors.
  • If you both choose rock, it's a tie.

It's too complicated!

It still might seem too complicated to program this game, so let's use a process called problem simplification where we solve an easier version of the problem, then as our understanding grows, we increase the complexity until we solve the entire problem.

One common way we simplify a problem is to constrain our input. If we force us to always choose 'rock', the program becomes a little easier to write.


In [ ]:
# 1. computer opponent select one of "rock", "paper" or "scissors" at random
import random
choices = ['rock','paper','scissors']
computer = random.choice(choices)

# 2. you input one of "rock", "paper" or "scissors"
# for now, make this 'rock'
you = 'rock' #input("Enter your choice: rock, paper, or scissors: ")
if (you in choices):  
    print("You chose %s and the computer chose %s" % (you,computer))
    
    # 3. play the game and determine a winnner (assuming rock only for user)
    if (you == 'rock' and computer == 'scissors'):
        print("You win! Rock smashes scissors.")
    elif (you == 'rock' and computer=='paper'):
        print("You lose! Paper covers rock.")
    else:
        print("It's a tie!")    
else: 
    print("You didn't enter 'rock', 'paper' or 'scissors'!!!")

Run the code in the cell above enough times to verify it works. (You win, you lose and you tie.) That will ensure the code you have works as intended.

Paper: Making the program a bit more complex.

With the rock logic out of the way, its time to focus on paper. We will assume you always type paper and then add the conditional logic to our existing code handle it.

At this point you might be wondering should I make a separate if statement or should I chain the conditions off the current if with elif ? Since this is part of the same input, it should be an extension of the existing if statement. You should only introduce an additional conditional if you're making a separate decision, for example asking the user if they want to play again. Since this is part of the same decision (did you enter 'rock', 'paper' or 'scissors' it should be in the same if...elif ladder.

You Do It

In the code below, I've added the logic to address your input of 'paper' You only have to replace the TODO in the print() statements with the appropriate message.


In [ ]:
# 1. computer opponent select one of "rock", "paper" or "scissors" at random
import random
choices = ['rock','paper','scissors']
computer = random.choice(choices)

# 2. you input one of "rock", "paper" or "scissors"
# for now, make this 'rock'
you = 'paper' #input("Enter your choice: rock, paper, or scissors: ")
if (you in choices):  
    print("You chose %s and the computer chose %s" % (you,computer))

    # 3. play the game and determine a winnner (assuming paper only for user)
    if (you == 'rock' and computer == 'scissors'):
        print("You win! Rock smashes scissors.")
    elif (you == 'rock' and computer=='paper'):
        print("You lose! Paper covers rock.")
    elif (you == 'paper' and computer =='rock')
        print("TODO - What should this say?")
    elif (you == 'paper' and computer == 'scissors')
        print("TODO - What should this say?")
    else:
        print("It's a tie!")    
else: 
    print("You didn't enter 'rock', 'paper' or 'scissors'!!!")

The final program

With the 'rock' and 'paper' cases out of the way, we only need to add 'scissors' logic. We leave this part to you as your final exercise.

Similar to the 'paper' example you will need to add two elif statements to handle winning and losing when you select 'paper' and should also include the appropriate output messages.


In [ ]:
# 1. computer opponent select one of "rock", "paper" or "scissors" at random
import random
choices = ['rock','paper','scissors']
computer = random.choice(choices)

# 2. you input one of "rock", "paper" or "scissors"
# for now, make this 'rock'
you = input("Enter your choice: rock, paper, or scissors: ")
if (you in choices):  
    print("You chose %s and the computer chose %s" % (you,computer))

    # 3. play the game and determine a winnner 
    if (you == 'rock' and computer == 'scissors'):
        print("You win! Rock smashes scissors.")
    elif (you == 'rock' and computer=='paper'):
        print("You lose! Paper covers rock.")
    elif (you == 'paper' and computer =='rock')
        print("TODO - What should this say?")
    elif (you == 'paper' and computer == 'scissors')
        print("TODO  - What should this say?")
    # TODO add logic for you == 'scissors' similar to the paper logic
    
    else:
        print("It's a tie!")    
else: 
    print("You didn't enter 'rock', 'paper' or 'scissors'!!!")

Metacognition

Please answer the following questions. This should be a personal narrative, in your own voice. Answer the questions by double clicking on the question and placing your answer next to the Answer: prompt.

Questions

  1. Record any questions you have about this lab that you would like to ask in recitation. It is expected you will have questions if you did not complete the code sections correctly. Learning how to articulate what you do not understand is an important skill of critical thinking.

Answer:

  1. What was the most difficult aspect of completing this lab? Least difficult?

Answer:

  1. What aspects of this lab do you find most valuable? Least valuable?

Answer:

  1. Rate your comfort level with this week's material so far.

1 ==> I can do this on my own and explain how to do it.
2 ==> I can do this on my own without any help.
3 ==> I can do this with help or guidance from others. If you choose this level please list those who helped you.
4 ==> I don't understand this at all yet and need extra help. If you choose this please try to articulate that which you do not understand.

Answer:


In [ ]:
# SAVE YOUR WORK FIRST! CTRL+S
# RUN THIS CODE CELL TO TURN IN YOUR WORK!
from ist256.submission import Submission
Submission().submit()