0

I have to Python scripts. In the first script I import the second script and need to pass a value to the second script. I tried the following:

test1.py:

import test2

test2.set_value(5)
test2.print_value()

test2.py:

value = None

def set_value(v):
    print("Set value: " + str(v))
    value = v

def print_value():
    print(value)

But the output is:

Set value: 5
None


I'm using Python 3.5

no0by5
  • 632
  • 3
  • 8
  • 30
  • `value` is local to `set_value`, you're not touching `value` in the global scope. Use `global` to do so. – Dimitris Fasarakis Hilliard Apr 25 '17 at 13:29
  • while `global` would fix your issue, it's usually highly recommended that you don't use `global`; rather you should pass value in to the function: `def print_value(value)` – MooingRawr Apr 25 '17 at 13:30
  • Thanks, I did'nt know about the global statement! @MooingRawr: I don't need to the script to print the function. I definitely need the value in the second script. – no0by5 Apr 25 '17 at 13:32
  • @no0by5 regardless of what you are doing with the value, you should be passing values into functions if the function needs to use those 'values'. Using `global` would get messy once your project becomes larger, it's not really a practical practice for scalability. – MooingRawr Apr 25 '17 at 13:34

0 Answers0