I am working on a guessing game in Python and would like some feedback on how the code looks. I am struggling a bit with it, particularly with the menu options and getting it to loop back to the menu again after it has written to a high scores txt file (haven't put in this part of the code yet).

Could you please look over the code and comment on what and where I need to improve them. Thanks in advance.

import random

input = "V" or "P" or "Q"
guesses = 0
guessesTaken = guesses +1
guess = number

print 'What is your name? '
yourName = raw_input()

def main():
    Input = 0
    menu = ''' Menu:\n
(V)iew High Scores\n
(P)lay Game\n
(Q)uit Game'''

    print menu
    try:
        a = str(raw_input(" : "))       
    except:
        print " Cannot convert input to string, please do not enter a number\n "

    while input != "V":    
        if input != "P" :
            input == "Q" 
            break
        else: print " Please choose V, P or Q\n"
        print menu
        a = str(raw_input(" : ")) 

if __name__ == "__main__":
    main()                

number = random.randint(1, 42)
print 'Please enter your guess, between 1 and 42: '

while guesses != number:

    if guess < number:
        print 'My number is higher.'

    if guess > number:
        print 'My number is lower.'

    if guess == number:
        break

if guess == number:
    guessesTaken = str(guessesTaken)
    print 'Good job, ' + yourName + '! You guessed my number in ' + guessesTaken + ' guesses!'

If you want a better code structure, you could write parts of the structure before the details. For example

import random

def main():
    name = get_name()
    while True:
        show_menu()
        answer = get_menu_choice()
        if answer == "P":
            play_game(name)
        elif answer == "V":
            view_high_scores()
        elif answer == "Q":
            break
        else:
            print("Please choose V, P or Q")

def show_menu():
    print (''' Menu:
(V)iew High Scores
(P)lay Game
(Q)uit Game''')

def get_name():
    pass # TODO

def get_menu_choice():
    pass # TODO

def play_game(name):
    number = random.randint(1, 42)
    guessesTaken = 0
    while True:
        try:
            guess = int(raw_input('Please enter your guess, between 1 and 42: '))
        except ValueError:
            print("Your guess must be an integer !")
            continue
        guessesTaken += 1
        if guess < number:
            print 'My number is higher.'
        elif guess > number:
            print 'My number is lower.'
        else:
            print 'Good job, ' + name + '! You guessed my number in ' + guessesTaken + ' guesses!'
            return

def view_high_scores():
    pass # TODO


if __name__ == '__main__':
    main()
commented: knows python very well +0

I put your program in a class which is useful if you need to use it later in a different program. The below comments explain a few pointers. If you have any questions just ask, classes can be confusing at first.

import random

#Code should always be in a method or class
#Don't have to convert a raw_input to a string, because it returns a string
#Always start varible names with lowercase, classes could be capitol

class GuessingGame:
    def __init__(self):
        self.menu = ''' Menu:\n
                        (V)iew High Scores\n
                        (P)lay Game\n
                        (Q)uit Game'''
        
    def getNameFromUser(self):
        print 'What is your name? '
        self.yourName = raw_input()

    def displayMenu(self):
        while True:
            print self.menu
            inpt = raw_input("Enter V, P, or Q\n");
            if inpt == "V":
                print "Add highscore list"
                #Will then have to create another method in this class to print highscroes
            elif inpt == "P":
                self.gameMode() #using self. to call method from inside the class
            elif inpt == "Q":
                return

    def gameMode(self):
        number = random.randint(1, 42)
        print 'Please enter your guess, between 1 and 42: '
        
        guess = -1
        self.guessesTaken = 0
        
        while guess != number:
            guess = int(raw_input('Enter Guess: '))
            if guess < number:
                print 'My number is higher.'

            elif guess > number:
                print 'My number is lower.'

            else: break #If found
            self.guessesTaken += 1

        if guess == number:
            print 'Good job, ' + self.yourName + '! You guessed my number in ',self.guessesTaken,' guesses!'


def main():
    game = GuessingGame() #Constructing the game
    game.getNameFromUser()
    game.displayMenu() #runs the menu, which then has all the options

if __name__ == "__main__":
    main()

Thanks for the fast response, both are excellent examples of well structured code. And thanks for imparting some knowledge to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.