Python Forum
name error with text based rpg code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: name error with text based rpg code (/thread-30511.html)



name error with text based rpg code - cris_ram415 - Oct-24-2020

I am getting a NameError in my text based rpg and I was wondering if anyone could help. Here's the code:

def chooseCoffee ():
    coffee = ""
    while coffee != "iced coffee" and coffee != "black coffee" and coffee != "cappuccino": # input validation
        coffee = input("Choose your coffee (iced coffee, black coffee, or cappuccino): ")


    return coffee
chooseCoffee()
if(coffee == "iced coffee"):
    print('Cashier: "Iced coffee it is!"')
Here's the error I get:

Error:
if(coffee == "iced coffee"): NameError: name 'coffee' is not defined
My goal is to get the program to print the message "(coffee) it is!"
If there's any way you could help me, I'd really appreciate it! Thanks


RE: name error with text based rpg code - cris_ram415 - Oct-24-2020

 if(coffee == "iced coffee"):
NameError: name 'coffee' is not defined


RE: name error with text based rpg code - bowlofred - Oct-24-2020

The variable coffee is defined inside the chooseCoffee() function. You can't refer to that variable outside the function. If you want to use information returned from the function you need to assign it to a variable. You could even make that variable coffee, but I'm going to use a different name to show it instead.

mycoffee = chooseCoffee()      # information stored in mycoffee in this section of code
if mycoffee == "iced coffee":  # don't need parenthesis here
    print('Cashier: "Iced coffee it is!"')



RE: name error with text based rpg code - cris_ram415 - Oct-25-2020

Awesome! Thanks so much! I now have a different problem, however. Even after using a valid input, it repeats the function twice. Here's my updated code:

def chooseCoffee ():
    coffee = ""
    while coffee != "iced coffee" and coffee != "black coffee" and coffee != "cappuccino": # input validation
        coffee = input("Choose your coffee (iced coffee, black coffee, or cappuccino): ")

    return coffee
chooseCoffee()
coffee = chooseCoffee()
if coffee == "iced coffee":
    print('Cashier: "Iced coffee it is!"')
elif coffee == "black coffee":
    print('Cashier: "Black coffee it is!')
elif coffee == "cappuccino":
    print('Cashier: "Cappuccino it is!')



RE: name error with text based rpg code - bowlofred - Oct-25-2020

On line 7 you run the function (but do nothing with the return value).
On line 8 you run the function again (and this time save the return value in "coffee")