mastermind
mastermind

Reputation: 1

Keep a game going until the user types exit, and print out how many guesses the user did?

I need to generate a random number from 1 to 9 and ask the user to guess it. I tell the user if its too high, low, or correct. I can't figure out how to keep the game going until they guess it correctly, and once they get it right they must type in exit to stop the game. I also need to print out how many guesses it took for them in the end. Here's my code so far:

import random

while True:

    try:

        userGuess = int(input("Guess a number between 1 and 9 (including 1 and 9):"))

        randomNumber = random.randint(1,9)

        print (randomNumber)

    except:

        print ("Sorry, that is an invalid answer.")

        continue

    else:

        break

if int(userGuess) > randomNumber:

    print ("Wrong, too high.")

elif int(userGuess) < randomNumber:

    print ("Wrong, too low.")

elif int(userGuess) == randomNumber:

    print ("You got it right!")

Upvotes: 0

Views: 997

Answers (3)

Fabrizio A.
Fabrizio A.

Reputation: 64

from random import randint

while 1:
    print("\nRandom number between 1 and 9 created.")
    randomNumber = randint(1,9)

while 1:        
    userGuess = input("Guess a number between 1 and 9 (including 1 and 9). \nDigit 'stop' if you want to close the program: ")
    if userGuess == "stop":
        quit()
    else:
        try:
            userGuess = int(userGuess)
            if userGuess > randomNumber:
                print ("Wrong, too high.")

            elif userGuess < randomNumber:
                print ("Wrong, too low.")

            else:
                print ("You got it right!")
                break
        except:
            print("Invalid selection! Insert another value.")

Upvotes: 0

Shubham Namdeo
Shubham Namdeo

Reputation: 1925

Here is the solution for your problem from:

Guessing Game One Solutions

import random

number = random.randint(1,9)
guess = 0
count = 0


while guess != number and guess != "exit":
    guess = input("What's your guess?")

    if guess == "exit":
        break

    guess = int(guess)
    count += 1

    if guess < number:
        print("Too low!")
    elif guess > number:
    print("Too high!")
    else:
        print("You got it!")
print("And it only took you",count,"tries!")

Upvotes: 0

dejanualex
dejanualex

Reputation: 4348

import random
x = random.randint(1,9)
print x

while (True):
    answer=input("please give a number: ")
    if ( answer != x):
        print ("this is not the number: ")
    else:
        print ("You got it right!")
        break       

Upvotes: 1

Related Questions