Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

My Solution to the Number Guessing game (the one where the user guesses)

Here's my own solution to the number guessing game:

import random
import os
import sys


def clear():
    os.system("cls" if os.name == "nt" else "clear")


def start_game():    
    # make a random number
    number = random.randint(1, 100)

    guessed_times = 0

    while True:
        # show how many guesses there is left
        print("You have {}/7 guesses.".format(guessed_times))

        # ask the user for a number from 1 to a 100
        try:
            guess = input("Guess a number from 1 to a 100: (press enter to quit) ")

            # if the user wants to quit, then quit the program
            if guess == "":
                print("Bye!")
                break

            guess = int(guess)
        except ValueError:
            print("Sorry, that isn't a number!")
            continue

        # tell the user if they need to guess higher or lower
        if guess > number:
            if not guessed_times > 6:
                print("Too high! Try a lower number.")
        elif guess < number:
            if not guessed_times > 6:
                print("Too low! Try a higher number.")
        # if the user got the number, tell the user that they won
        elif guess == number:
            print("You got the number! You win! The number was {}.\n".format(number))
            play_again = input("Want to play again? (Y/n) ").lower()
            if play_again == "n" or play_again == "no":
                print("Bye!")
                sys.exit()
            else:
                print("Here we go!\n\n")
                start_game()

        # if the user guessed more than six times, tell them that they lost
        if guessed_times > 6:
            print("Too bad! You lost. The number was {}.\n".format(number))
            play_again = input("Want to play again? (Y/n) ").lower()
            if play_again == "n" or play_again == "no":
                print("Bye!")
                sys.exit()
            else:
                print("Here we go!\n\n")
                start_game()
        guessed_times += 1
        print("")


# start playing
clear()
start_game()