7
def Input():
 c = raw_input ('Enter data1,data2: ')
 data = c.split(',')
 return data

I need to use list data in other functions, but I don't want to enter raw_input everytime. How I can make data like a global static in c++ and put it everywhere where it needed?

SilentGhost
322k67 gold badges312 silver badges294 bronze badges
asked Sep 12, 2010 at 11:03
2
  • 2
    You might consider not using these kind of global variables (hard dependencies), because they can make problems with testing and separation. Commented Sep 12, 2010 at 11:27
  • You can use data = raw_input('Enter data1,data2: ').split(',') Commented Sep 12, 2010 at 11:55

2 Answers 2

18

Add the global keyword to your function:

def Input():
 global data
 c = raw_input ('Enter data1,data2: ')
 data = c.split(',')
 return data

The global data statement is a declaration that makes data a global variable. After calling Input() you will be able to refer to data in other functions.

Sameer Alibhai
3,1984 gold badges37 silver badges36 bronze badges
answered Sep 12, 2010 at 11:10

2 Comments

If data is global do you need the line return data ?
Python gives an error when you define global variable from a function, if define at global level it doesn't get updated from a method.
4

using global variables is usually considered bad practice. It's better to use proper object orientation and wrap 'data' in a proper class / object, e.g.

class Questionaire(object):
 def __init__(self):
 self.data = ''
 def input(self):
 c = raw_input('Enter data1, data2:')
 self.data = c.split(',')
 def results(self):
 print "You entered", self.data
q = Questionaire()
q.input()
q.results()
answered Sep 12, 2010 at 12:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.