Phesus
Phesus

Reputation: 37

trying to make a menu for a program and run a specific function

i am trying to make a fortune cookie program and i need a menu, then the chosen option's function will be executed. i get an error when i try to run the code, i need to be able to run the function that is chosen (i have only written the code for option 1 as i came across this error: (i need to append the new fortune onto the end of the text file) Traceback (most recent call last): File "N:\work\computing\fortune cookie\fortunecookie.py", line 9, in if option == 1: NameError: name 'option' is not defined

def menu():
    print "Your options are: "
    print "1-Add a new fortune"
    print "2-Tell my fortune"
    print "3-Exit"
    option = raw_input("What do you want to do?")

menu()
if option == 1:
    addfortune()
elif option == 2:
    tellfortune()
elif option == 3:
    exitProgram()
else:
    print("Invlaid menu choice")
    menu()

def addfortune():
    newfortune = input("What is the new fortune?")
    f = open("fortune.txt","w")
    f.write(str(newfortune))
    f.close()
    menu()

Upvotes: 0

Views: 34

Answers (1)

user4446614
user4446614

Reputation:

It tries to access a variable from the global scope.

def menu():
    global option
    ...

The above code should do it.
Read more about scopes here

Maby try to return that value instead of using a global variable:

def menu():
    ...
    return option

And turn your conditions accordingly to it.

Some opinions about global variables: Why are global variables evil?

Upvotes: 1

Related Questions