0

So I'm a beginner, and this is for a class I'm taking. I know about return, but it's not letting me do what I'm trying to do in this piece of code

This is the function that contains the variable:

def disp_cookies():
    # This stuff is just for a print display
    inx = 0 # Displays list vertically 
    while inx < len(flavor_names):
        print("{}. {}".format(inx + 1, flavor_names[inx]))
        inx += 1

    valid_data = False
    while not valid_data:
        try:
            # This is the variable I need
            flavor = int(input("\nSelect a number for flavor> "))

            if 0 < flavor <= len(flavor_names):
                item_list.append(flavor)
                print(flavor_names[int(flavor) - 1])
                return flavor    # This is the return
                break

        except Exception:
            print("\nError. Please try again")
        else:
            print("\nPlease enter a valid response")

And here's where I'm trying to use the variable:

print("\n", flavor) # This is outside of the function in the previous snippet btw
print("\n{}s, {} box(es), ${} total".format(flavor_names[flavor - 1], qty_list[order_no], item_total))

This is the error I get:

Traceback (most recent call last):
  File "C:\Users\wiche\Documents\School\Python CIS122\L8_orderCost.py", line 95, in <module>
    print("\n", flavor)
NameError: name 'flavor' is not defined

I can get rid of the error by defining flavor outside of the function, but then the data in the variable is wrong when I use it. Any idea what I can do to fix it?

Keep in mind I'm an absolute beginner, what you see is basically all I understand of python so far

Thank you!

2 Answers 2

1

Variables inside functions disappear ("go out of scope") when the function returns.

To get a value out of a function, you need to do two things:

  1. In the function - return a value, or values.

  2. When you call the function - save the value, or values. You do that by setting a variable equal to the result of the function: flavour = display_cookies().

Consider this example:

def answer_to_life():
    answer = 42
    return answer

ans = answer_to_life()
print (ans)             # output: 42

Note that I've used a different variable name inside the function (answer) and outside (ans). You could use the same name, but that can confuse you early in your education.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response!! Now I'm having a new problem, though. I have the updated code as follows: flavor = disp_cookies() print("\n", flavor) print("\n{}s, {} box(es), ${} total".format(flavor_names[flavor], qty_list[order_no], item_total)) But now I get this error: IndexError: list index out of range Did I call the variable wrong somehow?
@tonberryking, please ask this as a separate question. It's hard to troubleshoot problems in comments - I can't copy-paste your code from a comment and run it! Reducing your program to a short, self-contained example will help you get a prompt response.
0

This is a scope problem. You have to variables called flavor. One in global scope and one in function scope.

If you want to access the global variable inside your function you need the 'global' keyword inside the function.

The other possibility is to assign the return value of your function to the global variable flavor.

Refer to [http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#more-about-scope-crossing-boundaries] for a complete explanation with examples.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.