python – 为什么我不能打印函数内声明的变量?

我正在尝试编写代码以在输入后显示英雄的属性.但它们在输出端都返回0

#This is one of code block that i use to calculate damage of heroes in Dota 2

def hero_attribute_input(hero_str,hero_agi,hero_int):
        print "Input the str of the hero"
        hero_str = int(raw_input("> "))
        print "Input the agi of the hero"
        hero_agi = int(raw_input("> "))
        print "Input the int of the hero"
        hero_int = int(raw_input("> ")) # Why can't you add a print commat here?
        return (hero_str,hero_agi, hero_int)

hero_str = 0
hero_agi = 0
hero_int = 0

hero_attribute_input(hero_str,hero_agi,hero_int)
#Why don't the variables change after this?

print hero_str
print hero_agi
print hero_int

最佳答案 虽然你可以把它变成全球性的,但这不是一个好习惯.而是这样做:

hero_str,hero_agi,hero_int = hero_attribute_input(hero_str,hero_agi,hero_int)

要解释这一点,您要更新变量,但这不会影响函数范围之外的变量.

因此,您需要使用您从函数返回的更新值重新分配变量.

return (hero_str,hero_agi, hero_int)

因此,完整代码应该或多或少如下:

def hero_attribute_input(hero_str,hero_agi,hero_int):
    print "Input the str of the hero"
    hero_str = int(raw_input("> "))
    print "Input the agi of the hero"
    hero_agi = int(raw_input("> "))
    print "Input the int of the hero"
    hero_int = int(raw_input("> "))
    return (hero_str, hero_agi, hero_int)

hero_str = 0
hero_agi = 0
hero_int = 0
hero_str, hero_agi, hero_int = hero_attribute_input(hero_str,hero_agi,hero_int)
print hero_str
print hero_agi
print hero_int

注:这是python 2.7上的运行代码,并且成功运行时没有错误.如果你仍然面临问题,那么问题出在其他地方.

点赞