First time posting to Code Review. Just looking to get some advice on how I can write better code.
I found the following exercise for a "Guess my Number" game on DaniWeb, but the linked source code file is no longer active. So while I know my code works, I'm not sure if I've written it in the best way.
"The computer randomly generates a number. The user inputs a number, and the computer will tell you if you are too high, or too low. Then you will get to keep guessing until you guess the number."
(I also added a limited number of tries to the game, so the user can't try 1-10 in order until they guess right.)
from random import randint
### Variable declarations
correct = False
tries = 0
number = randint(1,10)
###
print ("I'm thinking of a number between 1 and 10.")
print ("I'll give you 5 chances to guess it.\n")
# Ask the user for their guess, as long as there are tries remaining
# and they haven't already guessed correctly.
while correct == False and tries < 5:
guess = raw_input("What number am I thinking of?: ")
# Make sure user's input is an integer
try:
guess = int(guess)
if guess == number: # Correct answer
correct = True
print ("\nYou got it!")
elif guess > number: # Guess too high
if guess > 10:
tries += 1
print ("\nWay too high! Try a number 10 or lower.")
else:
tries += 1
print ("\nTry something lower.")
remaining = 5 - tries
print ("\nYou have " + str(remaining) + " guesses left.\n")
else:
if number > guess > 0: # Guess too low
tries += 1
print ("\nTry something higher.")
else:
tries += 1
print ("\nMake sure you guess a number 1 or higher!")
remaining = 5 - tries
print ("\nYou have " + str(remaining) + " guesses left.\n")
# Input not an integer
except ValueError:
print ("\nThat wasn't a number! Try again.")
print ("(I won't count that attempt.)")
remaining = 5 - tries
print ("\nYou have " + str(remaining) + " guesses left.\n")
### Game over! ###
# Ran out of guesses
if tries > 5:
print ("\nSorry, you ran out of guesses!")
print ("My number was " + str(number) + ".")
# Exited loop with tries left, must have guessed correctly
else:
print ("Well done. Thanks for the game.")
I'd love to get some feedback on what I have here. Thanks in advance!