Design

Monday, October 25, 2010

Guess the Number Game Python

With inspiration from InventWithPython.com, I wrote a game to guess a number between 1 and 20 with six attempts. This simple game is good practice for a beginner. My code is written in Python 2.6. The example from the link is written in Python 3 syntax.

import random

guessesTaken = 0

print 'Hello! What is your name?'
myName = raw_input() #get user name

number = random.randint(1,20) #random number between 1 and 20
print '%s I am thinking of a number between 1 and 20.' % myName

while guessesTaken < 6:
print 'Take a guess.'
guess = int(raw_input())
guessesTaken += 1
if guess < number:
print 'Your guess is too low.'
elif guess > number:
print 'Your guess is too high.'
else:
break #breaks out of loop

if guess == number:
if guessesTaken == 1:
print 'Good Job, %s! You guessed my number in 1 guess!'
else:
print 'Good Job, %s! You guessed my number in %d guesses!' % \
(myName,guessesTaken) #actual format on previous line without '\'


if guess != number:
print 'No. The number I was thinking of was %d' % number

3 comments:

  1. An alternative to:
    print 'Hello! What is your name?'
    myName = raw_input() #get user name

    is the combined form:
    myName= raw_input("Hello! What is your name?")

    ReplyDelete
  2. What if I enter a letter instead of a number ?

    ReplyDelete
  3. This code does not have exception handling, because I had not yet learned it. Caesar's Shift post from November shows how to test for a number, prompt for them to re-enter, and run the new input again if a number is not enterred

    ReplyDelete