# Random Number Guessing Game Code Efficiency - Python

UPDATE: I have added:

• a play-again option
• score keeping thing
• difficulty levels

**(but I still need help with the functions part).

I don't feel it's necessary to explain what my code does, as it is pretty self-explanatory. I have the entire program completed, but I need to put some of the components of the program into functions. I don't know how to do this. I also need to add a play again option (I have done this before, but for some reason this particular code isn't working...).

import random

#variables:
score = 0
play = True

while play:
while True:
try:
difficulty = int(input("Give me a number between 1 and 3 (these are the difficulty levels) \n\n 1 = easy \n 2 = medium \n 3 = hard \n\n"))
except:
print("This is not a number!")
continue

if difficulty > 3 or difficulty < 1:
print("That's an invalid input, please re-enter your number")
continue
break

number = random.randint(1, 10 * difficulty)
attempts = 0
guess = 0

while guess != number and attempts < 3:
attempts += 1
print("attempt number " + str(attempts))

while True:
try:
guess = int(input("Guess what number I am thinking of  "))
except:
print("That's not a number!")
continue

if guess > 10 * difficulty or guess < 1:
print("That's an invalid input, please re-enter your number.")
continue
break

if guess == number:
print("You guessed it correct!")
score += 1
elif abs(guess - number) == 1:
print("You're hot on the trail!")
elif abs(guess - number) <= 3:
print("You're getting warmer...")
else:
print("You're freezing cold!!")

if attempts == 3 and guess != number:
print("Oops! You've run out of guesses!")
print("The number I was thinking of was " + str(number) + ".")

print("Your final score is " + str(score))

text = input("If you want to play again, type 'yes' ")
if text != "yes":
play = False
print("Ok, thank you for playing!")

• I have done this before, but for some reason this particular code isn't working... Does the code work as intended? – theProgrammer Dec 3 '20 at 17:12
• I've actually got it figured out @theProgrammer but thanks for taking the time to look at my question! – fast_and_curious Dec 3 '20 at 20:04

I'm not exactly sure what you're asking but with my best guess, I'll give it a try.

What you should be turning into functions (in my opinon)

1. "bad" inputs (such as 'a', 'b' etc. or '%', '*' etc.); error trapping algorithm chunk of code into a function.

2. "You're hot on the trail" etc.) block of code can also be converted to a function.

My biggest concern with your program is the following:

if text != "yes":  then  play = False - Why just "yes"?? Why not "yes" and "Yes"?

What if the user inputs "Yes" - with a capital "Y" instead of "yes" - with a lower-case "y"? (I tried this by the way, and this was the output: "Ok, thank you for playing!"). For them (the user) they're indicating that they want to have another try at the game, but due to your code's incompetence for a variety of options (like "Yes" or "yes" - for replaying, "No" or "no" - for NOT replaying). Please solve this problem.

Now to your more imperative problem (the functions), I can give it a shot.

Note: You should aim for maximum clarity if you want your code to be re-used by others, or to make it easier to read and understand (not just for others but for you as well!).

if guess > 10 * difficulty or guess < 1:
print("That's an invalid input, please re-enter your number.")
# ⬆ this particular line!! ⬆
continue
break


You didn't specify WHY the input is invalid, you stated the obvious by saying "It's an invalid input"...be concise and again, aim for MAXIMUM clarity.

Note: I did abbreviate some of the variable/function names just for saving time.

Anyway, here's how I would've done this:

import random

#variables:
sc = 0
pl = True

# "bad" input loop function.
def get_num(diff):

while True:
try:
gs = int(input("Guess what number I am thinking of  "))
except:
print("Please enter a NUMBER. Letters (a, b...) and symbols (#, %...) are not appropriate vales.")
continue

if gs > 10 * diff or gs < 1:
print("Your number is not in the right range, please re-enter your number!")
continue
return gs

# "hot and cold" function
def temp_func(gs, num):

if gs == num:
print("CORRECT!")
return True
elif abs(gs - num) == 1:
print("HOT!")
return False
elif abs(gs - num) <= 3:
print("WARM")
return False
else:
print("COLD!")
return False

while pl:
while True:
try:
diff = int(input("Give me a number between 1 and 3 "
"(these are the difficulty levels) \n\n 1 = easy \n 2 = medium \n 3 = hard \n\n"))
except:
print("This is not a number!")
continue

if diff > 3 or diff < 1:
print("That's an invalid input, please re-enter your number")
continue
break

num = random.randint(1, 10 * diff)

attmp = 0
gs = 0

while gs != num and attmp < 3:
attmp += 1
print("attempt number " + str(attmp))

gs = get_num(diff)

did_win = temp_func(gs, num)
if did_win:
sc += 1
break

if attmp == 3 and gs != num:
print("Oops! You've run out of guesses!")
print("The number I was thinking of was " + str(num) + ".")

print("Your final score is " + str(sc))

txt = input("If you want to play again, type 'yes' ")
if txt != "yes":
pl = False
print("TYPE GOODBYE MESSAGE HERE")

• Ok wow @eker-luminous you're either a mind reader or you're just a super genius person. That is exactly what I needed!! Thanks a lot! Also, I'm sorry about my incompetent line of code, will make sure to fix that up (or attempt to). – fast_and_curious Dec 3 '20 at 20:03
• No worries, just keep the bold parts of my answer in mind. – esker-luminous Dec 3 '20 at 20:05
• Nice answer @esker-luminous. – theProgrammer Dec 3 '20 at 20:09
• Thank you @theProgrammer. I'm trying to help others while they help me :)) – esker-luminous Dec 3 '20 at 20:45

Here are a few quick comments and suggestions to start with. Rather than rewriting everything, I will start from what you wrote.

• The try/except statements at the bottom make no sense. A try is used to attempt to execute one or more lines of code that might trigger an exception (e.g. dividing by zero, trying to access an array element that is out of range, etc.). A break statement will never cause an exception, so the continue statement will never be executed. It behaves as if you just said "break" without the try/except and without the continue.

• Ignoring the above issue, your code is written to make two passes through the loop (attempts == 1 and attempts == 2). If you were hoping to go through the loop 3 times, then you should start with attempts = 0 or else use attempts <= 3 in the while statement. In all, if your try/except statement would be removed, you would ask for the number 6 times (3 times in each loop, 2 times through the loop).

• There is a concept called DRY (Don't Repeat Yourself). When you see repeated code, that is where a function makes sense. You take out the repeated code, put it in a function, and then call the function from the main loop. I extracted the code that was repetitive into a function. You will have to pass the number into the function so that it can tell if the user was correct. Then, you want the function to return whether the guess was correct.

• Next, rewrite your main body to take advantage of the function. I will change your WHILE loop into two separate loops: the outer loop to see if the user wants to play a game, and the inner loop to give them three attempts to get it correct. I'll do it in a mix of pseudocode (ALL CAPS) and real Python, leaving the final details for you.


import random

def get_user_guess(number):
guess = int(input("Guess what number I am thinking of: "))
if guess == number:
correct_guess = True
print("You guessed it correct!")
elif guess > number:
correct_guess = False
print("Guess lower!")
else:
correct_guess = False
print("Guess higher!")
return correct_guess

while True:

number = random.randint(1, 10)
guessed_correctly = False

# This loop will give the user three attempts, but break out of the loop if they guess correctly
for attempt in range(1, 4):
PRINT ATTEMPT NUMBER
if get_user_guess(number):  # This is the same as "if get_user_guess(number) is True"
guessed_correctly = True
break

if not guessed_correctly:
print("Sorry...)

ASK USER IF THEY WANT TO PLAY AGAIN
IF NO:
break
# otherwise, it will go through the loop again with a new game


There are a few other potential changes, but these are the major ones.

• thank you for this! will make sure ot use your suggestions to make my program better! – fast_and_curious Dec 3 '20 at 19:56