Guess my number - make it more efficient

Hey everyone,

I’m just starting out learning Python and I have learned a lot and decided to just google simple projects that I can test my skills out (in no way are these crazy or advanced).

One of the projects was a number guessing game - I’ve completed the project and made the code but I want to make sure that the code I am writing is clean, efficient and the best way to do it - I’m hoping perhaps you can take a look at my code and provide any pointers?

import random

def ranNum():
    randomNum = random.randint(1,20)
    return randomNum

numberOfGuesses = 0
ranNumStorage = ranNum()
answerFound = False

print(ranNumStorage) # to be deleted after testing

while numberOfGuesses < 5:
    if answerFound == False:
        userGuess = int(input('We\'ve picked a number between 1 - 20, what do you think the number is? '))
        if userGuess != ranNumStorage:
            numberOfGuesses += 1
            print('Sorry ' + str(userGuess) + ' is not the number.  You have ' + str(int(5-numberOfGuesses)))
        else:
            print('Great!, you guessed the right number in ' + str(numberOfGuesses) + ' and the number was ' + str(userGuess))
            answerFound = True
    else:
        break


Thank you in advanced!

1 Like

Here are my notes:

  1. For future reference, replace if answerFound == False with if not answerFound. Doing a Boolean comparison on a Boolean is a tad odd.

  2. 5 is an int and numberOfGuesses is also and int so 5 - numberOfGuesses is an int too. There is no need to cast an int to an int, just cast them to a string str(5 - numberOfGuesses)

  3. Instead of using the outer if else statement, change while numberOfGuesses < 5 to while numberOfGuesses < 5 and (not answerFound), do away with the outer if else statement and keep the rest of the code intact. Maybe just move the line where you increment the numberOfGuesses variable to the beginning of the while loop. Cause if the player makes a guess on the first attempt the number of attempts would be 0 which sounds a bit odd to me.

  4. This is no big deal in such a small and simple script, but when you get to complex projects, casting a variable of type A to type B (or any other repeated operation on variables) every single time it’s used can greatly increase processing time especially when it’s done inside a loop. The solution is to assign that to a variable. For example instead of converting the user’s guess to an int, and then converting it back to a string in the loop, assign the input to a variable x and then cast that to a variable y at the beginning and so on. userGuess = input (“guess a number”) and intUserGuess = int(userGuess). Then use each variable wherever it’s needed.

Happy coding!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.