开发者

How to get new value from function in Python?

开发者 https://www.devze.com 2023-03-19 12:13 出处:网络
If I put in \"Ab3\" as a parameter, how would I go about to having the value \"开发者_开发百科Ab4\" returned to me?

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)


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


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).


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

0

精彩评论

暂无评论...
验证码 换一张
取 消