-5

This is my experimenting code:

def settingValues():
  hi = "Hello"
  name = "Jake"
  isTrue = True

def callingValues():
  print(hi, name, isTrue)

settingValues()
callingValues()

Obviously this emmits an error... Is there an easy way to transfer the variables throughout the two functions? What I will be using this for requires setting quite a lot of variables... so I cant use 'global' for all of them. :)

Jake
  • 45
  • 2
  • 9
  • You can pass the variables as arguments to `callingValues` like `callingValues(hi, name, isTrue)` and then use them like normal variables. – Jose A. García Feb 19 '18 at 10:47
  • Wrap them in a class and use `self`? – tobias_k Feb 19 '18 at 10:47
  • 2
    Yes, you can, but this looks a lot like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Ma0 Feb 19 '18 at 10:48
  • Possible duplicate of [Access a function variable outside the function without using \`global\`](https://stackoverflow.com/questions/19326004/access-a-function-variable-outside-the-function-without-using-global) – AlokThakur Feb 19 '18 at 10:49
  • 2
    Those aren't "def statements", those are functions. This might sound like a nitpick, but is conceptually important. You want to *pass values into functions as arguments* and *receive return values* from them. You don't want to think at the level of variable names or "transferring" them. – deceze Feb 19 '18 at 10:52

2 Answers2

0

Just use OOP:

class SomeClass:
    def __init__(self):
        self.hi = "Hello"
        self.name = "Jake"
        self.isTrue = True

    def callingValues(self):
        print(self.hi, self.name, self.isTrue)

sc = SomeClass()
sc.callingValues()
Dmitrii K
  • 249
  • 2
  • 13
-2

The easiest way would be to define them as globals, which could then be accessed from all the functions in the same module

hi = ""
name = ""
isTrue = False
def settingValues():
    hi = "Hello"
    name = "Jake"
    isTrue = True

def callingValues():
   print(hi, name, isTrue)

settingValues()
callingValues()
ipop
  • 34
  • 4
  • 1
    Not only is this bad practice, it won't actually work. – deceze Feb 19 '18 at 10:50
  • To make variables global, you have to type the following code, not define them outside of a function. `global hi, name, isTrue` – Jake Nov 21 '18 at 03:42