-2

I need to create a variable in a different script from the main one in my game I am working on, with Python and Pygame.

For example:

def test():
    a = 10
def testing():
    return a

Then I run code like this:

import (script name)
script name.test()
script name.testing()

And after this, it gives an error. How can I fix this problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Welcome to Stack Overflow! Note: *it doesn't work* is a terrible problem description. Please be clear in your problem descriptions and include any error messages you see. – Martijn Pieters Oct 16 '13 at 07:24
  • This is also a very basic question; do read the Python tutorial again; names inside a function are local and are not seen by other functions. – Martijn Pieters Oct 16 '13 at 07:24
  • @Endoro: It is not a duplicate because one of possible answers to this question is to make an object `Test()` that encapsulates the value `a` then `t.test()` computes `self.a` and `t.testing()` can return it. It scales if there are many variables computed in `test()`. A practical example would be a configuration object that has a method to compute default values and methods to retrieve such values. "Scoping rules" won't suggest such answer. – jfs Mar 01 '14 at 10:09

1 Answers1

1

'a' in testing() is not a global variable and hence it's not recognised from previous function test(). If you really want to use 'a' from test() then you can probably define 'a' as Global Variable.

VIKASH JAISWAL
  • 828
  • 1
  • 5
  • 11