jueves, 22 de mayo de 2014

Guess the number, Part 1

For my first program, I'm going to do a "Guess the number" game. It's one of the most recommended first-game programs out there, so it feels like a good place to start.

Here's the most basic version:


from random import *

seed()

secretNumber = randint(1,10)

print("Welcome! I'm thinking of a number between 1 and 10. Can you guess what it is?")

answer = int(input("Your guess: "))

if answer == secretNumber:
   print("You are correct!")
else:
   print("I'm sorry, that's not correct.")
   print("The secret number was: " + str(secretNumber))

First of all, instead of import random, I prefer to do from random import *, so I can use seed() instead of random.seed() and randint() instead of random.randint().



I like to seed() before anything else in the program, because I tend to forget! For those who don't know what seed() does, I'll give a little explanation. Computers can't come up with truly random numbers. What it does is take a number and perform some operation on it. That first number the computer uses is called a 'seed'. You could use any number as a parameter for seed(), and if you leave it blank it uses the system time.

randint() just comes up with a random integer between 1 and 10, inclusive.

The most glaring problem with this program (and the kind of problem I hate the most) is that a user mustn't enter any value that isn't a number. To correct this we can do this:
from random import *

seed()

secretNumber = randint(1,10)

print("Welcome! I'm thinking of a number between 1 and 10. Can you guess what it is?")

### This is the new stuff ###

while True:
    try:
        answer = int(input("Your guess: "))
        break
    except:
        print("That's not a number.")

### /New Stuff ###
   
if answer == secretNumber:
    print("You are correct!")
else:
    print("I'm sorry, that's not correct. The secret number was: " + str(secretNumber))

Now we can't break the program!

The 'try' part is the python way of handling exceptions. I'm not very knowledgeable about the correct terminology, but an exception is when your program can't execute an order you give. Instead of letting the program crash you can 'catch' that exception and tell the program what to do in case it can't interpret a partiuclar line. In this case, it's going to try and turn your guess, which is initially a string, into an integer. If you happen to input a letter, which can't be changed into an integer, the interpreter will jump to the block of code following the 'except:' part.

We can make it a better game, though. We can let the player keep trying to guess the number until he gets it right, or wants to quit. Let's add this functionality:

from random import *

seed()

secretNumber = randint(1,10)

print("""Welcome to Guess the number!

When prompted, type your guess. If you want to quit, type \'q\'\n""")

print("I'm thinking of a number between 1 and 10. Can you guess what it is?")

while True: #This loop keeps going until the player wins or quits

    while True: #This loop keeps going until a valid answer is given

            answer = input("Your guess: ")
            if answer.upper() == 'Q':
                break
            else:
                try:
                    answerInNumerical = int(answer)
                    break
                except:
                    print("That's not a number.")
  
    if answer.upper() == 'Q':
        break
    elif answerInNumerical == secretNumber:
        print("You are correct!")
        break
    else:
        print("I'm sorry, that's not correct.")

I had to juggle around the 'try' block, and added a new variable, answerInNumerical. I actually ran into some trouble because this new variable doesn't get created if the answer isn't a number, so I had to make sure that any reference to it couldn't be reached if it in fact doesn't exist.

We'll keep optimizing this program in further posts. Keep on coding!

No hay comentarios:

Publicar un comentario