1
votes

I am having trouble with if statements in python. I am making a "game" entirely in dolan speak, excuse the spelling, it meant to be humorous manner. Sorry.

Here is the code:

import time

def menu():
    print ("dogz r a supar hahrd tin 2 matsr it tak yrs 2 mastr ut u nw git 2 exprince it. pik a tin 2 du:\n")
    menu = raw_input("1.)Ply Da Dogi gam\n2.)Halp\n")

    if menu == 1:
        game()

    if menu == 2:
        helpGame()

    if menu < 2:
        print ("dat not 1 ur 2 sry")
        time.sleep(1)
        menu()

def game():
    print ("nuw u ply mi gme u lke it")

def helpGame():
    print ("dis da halp u liek it")
menu()

That doesn't work for me, and I have never had direct function calling work inside of if statements and I have had to implement "seg-ways" which call the function.

Does this work for any of you? Is it possible it is my Python installation? Thanks!

2
That doesn't work for me - you need to be more detailed than that. It's worth pointing out that raw_input returns a string - and that you probably want int(..) and that... if menu < 2 will also execute if menu == 1... Think about using elif statements if criteria should be mutually exclusive... Other than that - not sure what else you're after... - Jon Clements♦
As a side note, calling menu recursively from menu like this is generally a bad idea. It's better to write this as a loop, which you break or return on a valid answer, instead of as a function that calls itself on an invalid answer. - abarnert

2 Answers

1
votes

raw_input() returns a string, you are using a number in your if statements, change this line:

menu = raw_input("1.)Ply Da Dogi gam\n2.)Halp\n")

to this:

menu = int(raw_input("1.)Ply Da Dogi gam\n2.)Halp\n"))

You will want to look in dealing with error conditions next though.

2
votes

As you add more options, the if statements get unwieldly. Try out this dictionary based structure instead.

def menu():
    print ("dogz r a supar hahrd tin 2 matsr it tak yrs 2 mastr ut u nw git 2 "
           "exprince it. pik a tin 2 du:\n")
    prompt = "1.)Ply Da Dogi gam\n2.)Halp\n"
    {'1': game, '2': helpGame}.get(raw_input(prompt), menu)()