TomKo
TomKo

Reputation: 129

How to get new value from function in Python?

If I put in "Ab3" as a parameter, how would I go about to having the value "Ab4" returned to me?

The goal of this function is to take the 3rd character of a string and add one to it, unless it is four, in which case it would not add one and just exit. I don't know how to obtain the "Ab4" that the function creates from "Ab3" and assign it back to the "area" variable.

def east(area):

    area_list = list(area)

    if "1" == area_list[2]:
        area_list[2] = "2"

    elif "2" == area_list[2]:
        area_list[2] = "3"

    elif "3" == area_list[2]:
        area_list[2] = "4"

    elif "4" == area_list[2]:
        cannot_go(why)

    else:
        exit(0)

    area = "".join(area_list)

Upvotes: 0

Views: 1640

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

You simply missed return statement in your function, you need it since you are using string input which is immutable. You can use the following code:

def east(area):
    if area[-1] in '123':
        return area[:-1] + str(int(area[-1])+1)
    elif "4" == area[-1]:
        print 'no way'
        return area
    else:
        return 'incorrect input'# or throw and exception depends on what you really need

EDITED as per Chris comment

Upvotes: 5

matte
matte

Reputation: 363

Python strings are immutable (http://docs.python.org/library/stdtypes.html), so you can't actually update the 'area' object (though you can reassign area to a new value as you've demonstrated). If you want the caller to get the new value, you should return the new area variable (return area).

Upvotes: 1

Chris Morgan
Chris Morgan

Reputation: 90842

What you've got there will work, you just need to return the value. Change the last line to return ''.join(area_list).

Upvotes: 0

Related Questions