As I’ve mentioned before, I’ve been spending Friday evenings programming with my 10-year-old, while his older sibling practices with his soccer team. We started out with python, did some work with Google Fusion Tables, and last week and this week again we’re back to Python. Someone at a recent THATcamp shared a link to Invent With Python and it’s been great fun for us to work through. So now instead of creating from scratch, we’re working through the examples and tweaking them here and there.
Here’s what we did to Chapter 4: Guess the Number. To run this code you’ll have to copy and paste it in a text editor, save it (numberguessing.py) and run it from the terminal (type: python numberguessing.py). You can really see my kid’s…uh…sense of humour… in these programs. Keep in mind he’s a beginner. I realize some line breaks, etc would add to the aesthetics, but I’m trying to reduce cognitive overload. One thing at a time!
# March 11, 2011. Mama & me
# based on _Invent with Python_ by Albert Sweigart
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
# This is a guess the number game.
import random
guessesTaken = 0
print('Hello! My name is Robo-Sam. What is your name?')
myName = input()
number = random.randint(1, 50)
print('Well, ' + myName + ', I hate that name, but I will let you play anyway. I am thinking of a number between 1 and 50. Normally you would get 10 guesses, but since I hate you, you only get 5.')
while guessesTaken < 5:
print('You will probably be wrong, but go ahead: take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Bad guess, Robo-Sam is laughing . Toooo Low.')
if guess > number:
print('Bad guess. What is wrong with you? Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('You were really lucky! Play again and place a wager ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. You ran out of guesses. Bwahahahaha! You failed...again. The number I was thinking of was ' + number)
You might argue that this makes my kid look pretty rotten, but I promise you, he really is a sweetheart.