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

时间:2015-11-18 17:12:43

标签: python function

我正在尝试编写代码以在输入后显示英雄的属性。但它们都在输出端返回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

2 个答案:

答案 0 :(得分:4)

它之所以不起作用,是因为如果你没有在你的函数中定义一个变量global,它就不会影响"外部"变量

可在此处找到一个很好的解释:Short Description of the Scoping Rules?

尝试将global hero_str添加到该功能中,这应解决问题。

hero_str = 0
hero_agi = 0
hero_int = 0

def hero_attribute_input(hero_str,hero_agi,hero_int):
    global hero_str
    global hero_agi
    global 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 command at here?
    return (hero_str,hero_agi, hero_int)


hero_attribute_input(hero_str,hero_agi,hero_int)

print hero_str
print hero_agi
print hero_int

或者抓住返回的值。我注意到Bhargav Rao打败了我,所以我在这个答案中没有通过这个。

答案 1 :(得分:3)

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

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

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