0

this is probably an easy answer and having to do something to do with global variables maybe? how can i get a user inputted data from one function and have it able to be called and outputted with other functions in the same program. For example:

hydro = False
    def main():
        medium = input("soil or hydro")

    def second():
        if medium == "hydro":
            hydro = True


main()
second()

2 Answers2

0

You could solve this problem using global variables: see here. However, it's a better practice in Python to use classes, and keep functions that share variables, along with the variables they share, in a particular class.

In your code, that would look something like this:

class MediumHandler(object):
    def __init__(self):
        self.hydro = False

    def main(self):
        self.medium = input("soil or hydro")

    def second(self):
        if self.medium == "hydro":
            self.hydro = True

handler = MediumHandler()
handler.main()
handler.second()

Notice the use of self. in each of the uses of medium and hydro. This attaches the variables to the object instead of leaving them in the global environment.

Community
  • 1
  • 1
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • oh yes i slightly remember classes now. Its been about 3 years since my studies at The University of Kentucky. So if i have 4 data inputs from the user, (CFL or HID ; HYDRO or SOIL ; Number of plants ; square footage.) would i then have to create 4 classes for each? – The High Closet Jan 24 '15 at 22:51
  • No, definitely not: you could store all of them as different variables in your class. Perhaps call it `InputHandler` or just `Input` rather than `MediumHandler`. – David Robinson Jan 24 '15 at 23:05
  • what is the def __init__(self): function for? – The High Closet Jan 24 '15 at 23:20
0

If you don't want to use classes then just make sure to use global variables:

hydro = False
medium = ''
def main():
    global medium
    medium = raw_input("soil or hydro: ")


def second():
    global medium
    global hydro
    if medium == "hydro":
        hydro = True

main()
print medium
second()
print hydro

Also note that I used raw_input() instead of input(). input wouldn't work for your case because you want the string to remain a string.

Abhinav Ramakrishnan
  • 1,070
  • 12
  • 22