Skip to content

Instantly share code, notes, and snippets.

@OCodingIsFunO
Last active January 12, 2019 13:06
Show Gist options
  • Select an option

  • Save OCodingIsFunO/9a1e7c3c74254a71c48cff2511f65ea1 to your computer and use it in GitHub Desktop.

Select an option

Save OCodingIsFunO/9a1e7c3c74254a71c48cff2511f65ea1 to your computer and use it in GitHub Desktop.
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Extras: Keep the game going until the user types “exit” Keep track of how many guesses the user has taken, and when the game ends, print this out.
#Imports random
import random
guesses = 0
game = True
#Generates random number
number = random.randint(1, 9)
print("You can type exit any time to quit!")
#While loops keeps game going as long as game is True
while game is True:
#It tries all the possibilties given
try:
#Here player enters their input
guess = int(input("Guess a random number form 1 to 9\n"))
#If guess is correct it prints out given message
if guess == number:
print("Correct guess!")
guesses += 1
print("You guessed " + str(guesses) + " times before you got it right![You can type exit any time to quit]")
#If guess is higher then number it prints out given message
elif guess > number:
print("You guessed too high!")
guesses += 1
#If guess is lover then number it prints out given message
elif guess < number:
print("You guessed too low")
guesses += 1
#If player types quit it breaks the loop
elif guess == "quit":
print("You quit the game.")
game = False
#If all the possibilites given can not be used because player typed a word not a number it prints given message
except ValueError:
print("You have to enter a number!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment