Using functions, conditional logic and external libraries to play games.

In the last assignment, we learned about functions and lists. In this walkthrough, we're going to add two more tools to our arsenal: External libraries and conditional logic.

External libraries are code that is not in the standard library that performs a common task. For instance, choosing something at random is a common task, but not so common that it's built into Python's standard library. It's in an external library, conveniently called random that helps us choose something at random.

Conditional logic uses terms like if and else to guide us through decisions. We can puzzle through conditional logic with words -- if this is greater than that, do this. Else, do this other thing. If we need more than one else, we use elif, which is the same as saying if this is greater than that, do this, else if that is greater than this, do this thing, else do something completely different.

Let's apply these things using a simple game: Heads or Tails.

The first thing we do in any Python script is we import the libraries we need. In this case, we need the random library. To import a library we simply do this:


In [3]:
import random

Easy, right?

So the next thing we need to do is to remember that in coding, before we can do anything, we need to create the things we need to do what we want. In this case, we need to create the coin, and it needs to have two sides: heads and tails. We can do this simply with a Python list.


In [4]:
coin = ["heads", "tails"]

Now, to make this a game, we can take input from a user using a function called raw_input. That looks like this:


In [9]:
call = input("Call it in the air: heads or tails: ")


Call it in the air: heads or tails: heads

Now we have a variable called call that we can compare to our random choice. To have Python choose a random choice, it looks like this:


In [10]:
flip = random.choice(coin)
print("It is %s" % flip)


It is tails

Now we need to determine if we win or not. We can do that with conditional logic. It take this form: if comparison between two things is what we want, do thing, else do other thing. In code, it looks like this:


In [11]:
if call == flip:
    print("You win!")
else:
    print("Sorry. Better luck next time!")


Sorry. Better luck next time!

Assignment

I want you to write a simple Python script that plays Rock Paper Scissors against itself using random choices. To do this, you will need to do the following.

  1. Use the random library.
  2. Define choices.
  3. Define a function that makes a choice.
  4. Make choices for each player randomly.
  5. Define a function that determines a winner using conditional logic.

And then you'll need to play the game.

Bonus points: How would you set it up to determine a winner of two out of three?


In [ ]: