By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,019 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

Passing a Function Variable to Global Variable

P: 1
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:

Expand|Select|Wrap|Line Numbers
  1. #This is my GLOBAL Variable to be used later
  2. FRUIT = "apple"
  4. def setFruit ():
  5.    fruit = raw_input("What fruit do you want?")
  6.    FRUIT = fruit #An attempt to store the value the user typed to the Global Variable
  8. def getFruit():
  9.    print FRUIT
  11. setFruit()
  12. 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!
Oct 3 '06 #1
Share this Question
Share on Google+
1 Reply

Expert 5K+
P: 6,596
Expand|Select|Wrap|Line Numbers
  2. def setFruit ():
  3.    global FRUIT
  4.    fruit = raw_input("What fruit do you want?")
  5.    FRUIT = fruit #An attempt to store the value the user typed to the Global Variable
Oct 3 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.