# Beginning guessing game in Python

I've just finished work on my guessing game. I'm still fairly new to Python, so I'm looking for feedback and criticism on the code.

def game():

import random #imports the module 'random'

yes={"Yes","Y","yes","y"} #set 'yes' to these 4 strings
no={"No","N","no","n"} #set 'no' to these 4 strings

secret=int(random.random()*10)+1 #randomly generate a number

trynum=0 #sets the number of tries to 0

print ("---------------------------------------------------------------------\n"
"---- Welcome,",name+"!\n"
"---- I am thinking of a number between 1 and 10.\n"
"---- Lets see how many times it will take you to guess the number.\n"
"---------------------------------------------------------------------\n")

while True: #starts a loop

trynum=trynum+1 #sets number of tries to itself + 1

guess=int(input("What is guess #"+str(trynum)+"? \n")) #asks for a guess

if guess<secret: #if guess is too low/less than(<)
print ("Too Low. Try again!")

elif guess>secret: #if guess is too high/greater than(>)
print ("Oops!! Too high, better luck next try!")

else:
if trynum==1: #if number of tries is only 1
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guess!\n"
"-------------------------------------------------\n")
else: #if number of tries is anything else
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guesses!\n"
"-------------------------------------------------\n")

if trynum<3: #if guessed in less than 3 tries
print ("Bravo!")

elif trynum<5: #if guessed in less than 5 tries
print ("Hmmmmpf... Better try again")

elif trynum<7: #if guessed in less than 7 tries
print ("Better find something else to do!")

else: #if guessed in more than 7 tries
print ("You should be embarssed! My dog could pick better.")

choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
game()
if choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
break
game()


Good job for a first experience in Python! You can improve your code a little by looking at these recommendations:

• To choose a random integer, you could simply use random.randrange(0,11)
• You should probably not import at the function level either, try writing your import statements at the top of your file.
• The game() function is called recursively; you shouldn't do that. You could have an infinite loop that fires game() back when exited.
• Personally, I wouldn't use lists with "yes" and "no" values, try something like

if "y" in choice.lower():
return True
else:
return False

• Last but not least, you should check if the number entered is an integer. If it is not, ask the user to enter a valid integer until they do so.

• Rewriting the same post over and over from a mobile looks decently frustrating :P Want any help? May 22 '16 at 21:40
• Yes, of course :D I have trouble getting the code properly displayed. Plus, I'm having a hard time trying to find grammar / orthographic mistakes May 22 '16 at 21:41

• As noted by WayToDoor in his preliminary draft, you import inside your function. There are some cases where this is useful behavior as it means you'll only import a module when your function needs it, however it is generally encouraged that you put your imports at the top of the file.
• The Python random module has a function called randint which will generate a random number for you in the specified range.
• You have a lot of nested if statements. Your code might look neater if you rethought what you're doing so that the logic is flat.
• Take a look at this PEP8 style guide checker. PEP8 is the recommended style for Python code to ensure some measure of readability and consistency is present in your code.
• Scottbb describes a way to refactor this code so that more useful information can be gained from the play_game method and the code is grouped more logically.

Just because I think large bullet-pointed lists are a bit blah, here's some code to think on.

import random

def play_game(name, lower=1, upper=10):
"""
Play a number guessing game!
:param name: The name of the player
:param lower: The lower limit of numbers to be guessed greater than or equal to 0
:param upper: The upper limit of numbers to be guessed greater than the lower limit.
:return: A boolean that determines whether the player wants to play again.
"""
# Generate a random number in the given range, inclusive.
secret = random.randint(lower, upper)
number_of_tries = 0

print("---------------------------------------------------------------------\n"
"---- Welcome, {}!\n"
"---- I am thinking of a number between {} and {}.\n"
"---- Let's see how many times it will take you to guess the number.\n"
"---------------------------------------------------------------------\n"
.format(name, lower, upper))

# Main loop
guessing_numbers = True
while guessing_numbers:
guess = input("What is guess #{}?\n".format(number_of_tries))

# Make sure that the user enters a valid number.
while not guess.isdigit():
print("Sorry, that isn't a valid input.")
guess = input("What is guess #{}?\n".format(number_of_tries))

# Now that we can assume it's a valid number,
# we can turn the string into an integer.
guess = int(guess)
# Increment the number of tries by 1
number_of_tries += 1

if guess < secret:  # If the guess is too low
print("Too Low. Try again!")
elif guess > secret:  # If the guess is too high
print("Oops! Too high, better luck next try!")
else:  # They've guessed the correct number!
guessing_numbers = False  # Break out of the loop

if number_of_tries == 1:
guess_form = "guess"
else:
guess_form = "guesses"

print("-------------------------------------------------\n"
"---- {}! You got it in {} {}!\n"
"-------------------------------------------------\n"
.format(name, number_of_tries, guess_form))

if number_of_tries < 3:
print("Bravo!")
elif number_of_tries < 5:
print("Hmmmmpf... Better try again")
elif number_of_tries < 7:
print("Better find something else to do!")
else:  # They took more than 6 tries.
print("You should be embarrassed! My dog could do better.")

choice = input('Would you like to play again? ("yes" or "no")\n')
if 'y' in choice.lower():
return True  # They want to play again.
else:
print("Okay.. Goodbye :(")
return False  # They don't want to play again.

def main():
# Get the user's name so we can address them.
name = input("What is your name?\n")
playing = True
while playing:
playing = play_game(name)

# This means you can import the code without running it or
# if you want to you can run the code like an executable.
if __name__ == "__main__":
main()


I had basically written everything Zenohm wrote (but way too wordier). I would like to suggest the slight change to Zenohm's code.

Remove the end of play_game(), from choice = input(...) on, and move that logic to main():

def play_game():
...
# deleted everything from 'choice = input(...)' on
return number_of_tries

def main():
name = input("What is your name? \n")  # Asks the user for their name
results = []
while (True):
results.append(play_game(name))
choice = input('Would you like to play again? ("yes" or "no")\n')
if 'y' not in choice.lower():
break

# do something with the list of results from gameplays,
# such as printing the average number of tries
average = float(sum(results))/len(results)
print("On average, it took you {} tries to guess.".format(average)

# This means you can import the code without running it or
# if you want to you can run the code like an executable.
if __name__ == "__main__":
main()


This cleanly separates the business logic of the game from the mechanics of running the game multiple times. Also, it frees up play_game() to return the number the number of guesses the user took, so that main() (or other calling code, in the future) can collect statistics about gameplay.

• That's a pretty good idea! I'll leave my code as it is though and point to your addition so you didn't waste your time :) May 22 '16 at 23:38
• I think all of this will help me a lot. I'll work on it with you guys' suggestions. I'll come back and post an updated version when I finish. Thank you all so much for your suggestions thus far. I'm still fairly new to Python, so all of this is helping very much. May 23 '16 at 16:53

Besides the great commentary given by WayToDoor (which Zenohm wrote up), I'd just like to remark on your commenting style.

The comments are quite superfluous, stating exactly what the code is doing, and as such do not add any value.