3

I have the following code:

def thingy(res)

    if res=="food":
        res=0
    if res=="wood":
        res=1
    if res=="metal":
        res=2
    if res=="gold":
        res=3
    if res=="oil":
        res=3

res="food"

thingy(res)

print(res)

When I run this it comes up with "food" when i want it to say "0". how can i get this to work? Many thanks if you are able to help me.

3 Answers3

8

You need to return the value, and why not to use dictionary instead of all the if statements, They are the best for this kind of problems:

Example:

def thingy(res):
    myOptions = {'food':0, 'wood':1, 'metal': 2, 'gold': 3, 'oil': 3}
    return myOptions[res]

res = "food"
res = thingy(res)
print(res)
Eric
  • 95,302
  • 53
  • 242
  • 374
Kobi K
  • 7,743
  • 6
  • 42
  • 86
5

Assigning to res inside the function only changes the parameter res; this does not affect res outside the function.

Make the function return the result. Assign the value of the function to the variable.

def thingy(res):
    if res=="food":
        res=0
    if res=="wood":
        res=1
    if res=="metal":
        res=2
    if res=="gold":
        res=3
    if res=="oil":
        res=3
    return res # <---

res="food"
res = thingy(res) # <---
print(res)
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

Usually, what you want is to assign the return value to the variable:

res = thingy(res) # instead of thingy(res)

But if you want another option, perhaps you're looking for a global variable?

def thingy():
    global res
    if res=="food":
        res=0
    if res=="wood":
        res=1
    if res=="metal":
        res=2
    if res=="gold":
        res=3
    if res=="oil":
        res=3

res = "food"
thingy()
print(res)  # prints "0"

In your example, the res inside your function is not the same res that you defined outside of your function (you could give one of them a different name and it wouldn't matter). In this example, it is, because of the line global res.

But in most cases it's simpler and clearer to use the return value.

ColBeseder
  • 3,579
  • 3
  • 28
  • 45