Skip to content

Number Guessing Game

Daniel Gamboa edited this page Feb 13, 2017 · 11 revisions

Overview

Be a psychic and guess what number the computer is thinking!

In this lesson, we get a more in-depth look at loops and introduce the use of user-defined functions to our repertoire.

We put this knowledge to the test in this lesson by coding a number guessing game. In this guessing game, players must guess a number that is randomly chosen by the computer from 1-100.

New Concepts

Loops:

By now, you should have already had a bit of experience writing loops.

In python, there exists two types of loops:

  • for
  • while

Equivalent examples of each are shown below:

    pizza = ["cheese", "pepperoni", "sausage", "pineapple", "ham"]

    for topping in pizza:
        print(topping)

    count = 0
    while count < len(pizza):
        print(pizza[count])
        count = count + 1

When you run these loops, you will notice that we get the exact same output. A for loop is used to repeat whatever code is within in a certain number of times. A while loop is used when we need to run the code within it until a particular condition occurs. However, a while loop can do whatever a for loop can but not vice-versa. The advantage of using a for loop is that it is much more simple to read and write.

Here are more loop examples:

for item in ["a","b","c"]:
    print(item)

for num in [0,1,2]:
    print(num*2)

for num in range(5): #What is range?
    print(num)

aString = "hello"
for c in foo:
    print(c)

In case you didn't notice, we used a built-in function called range() which can be used different ways:

  • range(end)
  • range(start, end)
  • range(start, end, step)
range(2,19,3)
#Output: [2,5,8,11,14,17]

Functions:

We have also seen a couple of these in the past such as: print(), input(), int(), str(), range()

But, these are built-in functions. So how do we define our own?

def function_name(arguments):
    #function_body

Functions can have return values...

We can also use functions from within other functions...

def bar():
    print("inside bar")

def foo():
    print("inside bar")
    bar()

bar() #What prints out?
foo() #What about here as well?

Finally, why does this matter? <Extracts routine to a function to reuse code. Convey the practicality and advantages of reusing code, clarity of modularity.>

Let's Get Started

First, let's open up a new file and save it as: guess.py Then, write the following:

import random #This is necessary for generating a random number

#Any additional methods you write should go up here

def main():
    print("Guess a number from 1-100!") #This is just a welcome print statement
    
    #The main game loop should be here

if _name__ == '__main__':
    main()

Now that everything has been set up, let's go over the list of things that happens in our game..

  1. The computer generates a random number (this is the number we will be trying to guess).
  2. Player inputs their guess.
  3. The program checks to see if the player's number is..
    • Higher?
    • Lower?
    • Or just right 👌
  4. Based on the response, does the game continue? or is it done?

Sample Output

Guess a number from 1-100!
Enter a number: 50
Too low...

Enter a number: 75
Too low...

Enter a number: 87
Too low...

Enter a number: 94
Too high!

Enter a number: 91
You got it!

Stretch Goals

1. Limited tries!

Let's make the game a little harder! Using what you've learned thus far, implement a way that our program restricts the number of guesses the player can make. In other words, give the player "lives" or, chances they have to guess until they lose the game.

2. Choose your opponent!

This is just a simple addition. Create a function called chooseOpponent(choice) that passes in the player's choice of either "human" or "computer". If human is picked, your program should obtain input of whatever number is chosen to guess. Otherwise, if it's computer, generate a random number as usual. Don't forget to return the number the opponent (human or computer) chooses.

Extra: Hangman [Work-in-progress]

Extra: Game of Pig [Work-in-progress]

  • Rules: Two players race to reach 100 points. Each turn, a player repeatedly rolls a die until either a 1 is rolled or the player holds and scores the sum of the rolls (i.e. the turn total). At any time during a player's turn, the player is faced with two decisions:

    • roll - If the player rolls a
      • 1: the player scores nothing and it becomes the opponent's turn.
      • 2-6: the number is added to the player's turn total and the player's turn continues.
    • hold - The turn total is added to the player's score and it becomes the opponent's turn.