Passing a Function Variable to Global Variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SolitudeX
    New Member
    • Oct 2006
    • 1

    #1

    Passing a Function Variable to Global Variable

    Hey there,

    I have just started to learn the programming basics. Python looked like a good starting point! I have run into a little snag that I can't seem to find an answer for that I could use some help with!

    I understand that any values or variables created/defined within any given function are destroyed when the function has finished executing. However, what I am trying to do is to get the value of a function variable to be stored in a 'Global' variable outside of the function so that it can be used again later.

    An example would be:

    Code:
    #This is my GLOBAL Variable to be used later
    FRUIT = "apple"
    
    def setFruit ():
       fruit = raw_input("What fruit do you want?")
       FRUIT = fruit #An attempt to store the value the user typed to the Global Variable
    
    def getFruit():
       print FRUIT
    
    setFruit()
    getFruit()
    The output I would hope for is that the user might have said "orange" to what fruit they wanted, then later when the getFruit() function is called, it reads the value of FRUIT and displays it. In this case, it would change the value of FRUIT from apple to orange and remember it for later use.

    Any help would be appreciated! Thanks in advance!
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Code:
    def setFruit ():
       global FRUIT
       fruit = raw_input("What fruit do you want?")
       FRUIT = fruit #An attempt to store the value the user typed to the Global Variable

    Comment

    Working...