1

I have the following scripts:

the first is test1.py

x = 1

def test():

    globx = x
    print(globx)
    globx += 1
    return globx

x = test()

and the second is test2.py

import test1

z=3
while z != 0:
    if __name__=='__main__':
        test1.test()
        z -= 1
    else: 
        pass

I'm using these to learn and play about with calling functions from other scripts, what I want is the output:

1
2
3

but I get:

1
2
2
2

when I replace the

    globx = x
    print(globx)
    globx += 1
    return globx

x = test()

in test1.py with

global x 
print(x) 
x += 1

I do get the desired outcome but apparently you shouldn't use global variables so it's a habit I'd like to break.

I have 2 questions.

  1. Why do I get the wrong output and
  2. Why are there 4 outputs when I use the globx = x version of test1.py instead of 3?

2 Answers 2

2

Why do I get the wrong output?

When you import test1 is runs for the first time, executing test for the first time and assigning it to x, printing 1 and incrementing x.

Then you execute test another 3 times inside test2, but without updating x, so test will set globx with x, print x and update globx, yet leaving x untouched (stuck on 2).

Why are there 4 outputs?

You set z to 3, then count to 0. z = 3, 2, 1, 0 OVER!. So you execute for z = 1..3, resulting in 3 times + the time that executes inside test1 itself, when loaded.

How to fix?

On test1.py:

Use global x for all actions. Don't run test:

x = 1

def test():
    global x
    print(x)
    x += 1

On test2.py:

Iterate 3 times with range. Your else: pass would trigger infinite loop if the module was run by another one:

import test1

if __name__ == '__main__':
    for _ in range(3):
        test1.test()
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, this works well but I was hoping to avoid using global
You could use generators, but that would be more complex. How else did you thought of keeping the current value without a global?
by using return globx and then setting x = test()
that would work only if you set x manually every time you call test (test1.x = test1.test()), and technically, x would still be a global.
Ahh I see. Would there be a way of sending x or any other variable say by using input() or just setting it into test1 from test2
|
0

When you import test1, the whole script is executed. The function test() is called for the first time. It prints 1 and changes x to 2. Then you call test1.test() three times in the loop. globx is a local variable. It is printed three times (2) and changed three times to 3, but the changes are not saved.

Comments

Your Answer

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.