Waleed Qutob
Waleed Qutob

Reputation: 57

Python Raspberry PI Guessing Game(Function call not working)

My problem is that my Random function doesn't get called from the Menu function. I've tried everything, but it still doesn't work. It's weird, because i think that i have structured the functions correctly, and everything should work fine, but it doesn't call Random.

def Menu():
    name = raw_input("What's your name?\n:")
    print "Hello, %s!\nWeclome to the Guessing Game!" % name
    print "Select an option:"
    print "1- Guess a number between 1-100."
    print "2- Guess a number between 1-1000."
    print "3- Guess a number between 1-10,000."
    print "4- Guess a number between 1-100,000."
    print "5- Exit."
    try:
        selection = raw_input("Enter your selection:")
        if selection == 1:
            Random(100)
        elif selection == 2:
            Random(1000)
        elif selection == 3:
            Random(10000)
        elif selection == 4:
            Random(100000)  
        elif selection == 5:
            exit()
    except:
        os.system("clear")
        print "Sorry, that wasn't an option. Enter your selection again."

Menu()

Upvotes: 0

Views: 219

Answers (1)

Psytho
Psytho

Reputation: 3384

raw_input() retuns a string so you have to cast the input to int or compare the input with strings. Either this way:

selection = raw_input("Enter your selection:")
if selection == "1":
    Random(100)
elif selection == "2":
    Random(1000)
elif selection == "3":
    Random(10000)
elif selection == "4":
    Random(100000)  
elif selection == "5":
    exit()

or this way:

selection = raw_input("Enter your selection:")
if int(selection) == 1:
    Random(100)
elif int(selection) == 2:
    Random(1000)
elif int(selection) == 3:
    Random(10000)
elif int(selection) == 4:
    Random(100000)  
elif int(selection) == 5:
    exit()

Furthermore you can avoid try by kicking out elif int(selection) == 5: and using else:" instead. So the game will be ended with any other input than 1,2,3 or 4. There will be no possibility to "enter your selection again" after calling except in your code anyway because the script stops.

The function Random is not very optimal. See this:

    def Random(select): 
        range = "1-" + str(select)
        Correct_Guess = random.randint(1,select+1)
        Difficulty()

It is the same but shorte and more readable ;)

Upvotes: 1

Related Questions