Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't I print variables declared inside a function?

I am trying to write a code to display atribute of the hero after the entry. But they all return 0 at the output

#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
like image 504
An Pham Avatar asked Mar 15 '23 03:03

An Pham


1 Answers

The reason why it isn't working, is because if you don't define a variable as global within your function, it will not affect "outside" variables.

A good explanation can be found here: Short Description of the Scoping Rules?

Try adding global hero_str to the function and that should solve the issue.

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

Or catch the returning values. I noticed Bhargav Rao beat me to it, So i won't go through that in this answer.

like image 172
Torxed Avatar answered Mar 23 '23 02:03

Torxed