0

I have a created a variable at the start of my program, and another in a def before an important IF. However, I keep running into problems with reading & writing them.

I have the following code snippet:

#(...)
move_to = "finishedImages"
amount_moved = 0

def put_in(is_training:bool, file:Path):
    pthstr = file.__str__()
    target = move_to
    if is_training:
        target = target + "/train" # Makes a local instead!
    else:
        target = target + "/test" # Makes a local instead!

    shutil.move(file, move_to )
    shutil.move(pthstr[:len(pthstr) - 3] + "jpg", move_to)
    amount_moved += 1 # Can't even read amount_moved!
#(...)

My problem is that the IF does not override the target variable but insted creates a new local one, despite the fact it can read it. In effect, these lines become useless as my program continues to use the old target value.

Furthermore, the amount_moved cannot be accessed.

I'm more used to other languages where the scope system is rather simple such as Java, help!

  • 1
    "_cannot be accessed_"? You mean it simply does not get incremented, or that you get a runtime error? Any diagnostics output should be included in the question. – Clifford Jan 13 '23 at 10:32
  • Sorry, with that I meant to say it cannot be resolved – AverageJoe1245 Jan 13 '23 at 10:37
  • 1
    You can read global variables in your function, but when you do `amount_moved += 1` you define a new local variable. There is the `global` keyword, but changing a global variable in a function is a bad idea in over 99% of all cases where it is used (yes, this is one of thise cases). Use a different variable and return it at the end of the function. – Matthias Jan 13 '23 at 10:42
  • Thank you! I just solved it using globals, but made a different solution according to your input. Can I add my solution here? The question is closed so I can't respond, should I edit my question instead? – AverageJoe1245 Jan 13 '23 at 10:49
  • What would your solution add over anything already mentioned in the duplicate? – deceze Jan 13 '23 at 10:54
  • A nice solution to the problem that should be easy to understand for Python beginners like me. I couldn't really find any good examples. The duplicate's answer lacks the completed code. – AverageJoe1245 Jan 13 '23 at 10:58
  • https://stackoverflow.com/a/370364/476…?! – deceze Jan 13 '23 at 11:03
  • Ah, I didn't see that. I still think it'd be nice to have full solutions with- and without globals, but if you deem it unnecessary then let's leave it at that. And thanks for the help again! – AverageJoe1245 Jan 13 '23 at 11:06

0 Answers0