Skip to main content
edited tags
Link
Mathieu Guindon
  • 75.6k
  • 18
  • 194
  • 468
Source Link
Akar
  • 369
  • 4
  • 12

Python number guessing game

I'm a PHP Developer. I'm trying to learn Python. So I tried to create a simple game, a Number Guesser.

I tried to comment out as much as possible without making super obvious comments.

I also made the attempts message color to be red.

Here's my code.

# 1. Print a message about the game
# 2. Tell the user that the random number is between some numbers
# 3. Run a while loop to continue the input, break the loop when the guess is right.
# 4`. When the user guessed the number, tell them that they're right.

import random

# Simple message to the user.
print "Welcome to the Number Guesser game."
print "I have a number in my mind that's between 1-20."

number = random.randint(0, 20)

# Guess the number
# > 
prompt = "> "

# Start out as 5 and then decrement it on wrong guesses.
attempts = 5


while attempts > 0:
    print "What's your guess? "

    # Simple validation
    try:
        guess = int(raw_input(prompt))
    except ValueError: 
        print "Only numbers are allowed. \n"
        break

    if guess > number:
        print "Go lower."
    elif guess < number:
        print "Go higher."
    else:
        print "Nice! You've guessed it right. The number was %d." % number
        print "And you got it with %d attempts!" % attempts
        # Exit.
        break

    # Decrement the attempts each time the guess isn't right.
    attempts -= 1


    if attempts == 0:
        print "You didn't guessed it, the number was %d. You lose." % number
        # Exit the script.
        break
    # Print with the color red.
    print("\033[91m You have {} guesses left. \033[00m").format(attempts)