0

Is there a way to create global variables using a For loop and then be able to reuse this variable inside and outside that loop?

I'm looking to achieve something like this:

for x in for_loop:
  global variable_1
  variable_1 = some_value
  variable_2 = some_other_value
  print(f"{variable_1} added to: {variable_2}")

print(f"{variable_1} added to: {variable_2}")

I've been browsing for hours to find a way to do this and I can't figure it out.

First, is it possible? Second, is it a good idea/way to go about this?

Each variable would have code like this:

clip1_audio = VideoFileClip("1.mp4").audio
clip1_audio = clip1_audio.audio_fadein(1).audio_fadeout(1)
clip1 = VideoFileClip("1.mp4").set_audio(clip1_audio)
clip1 = clip1.set_start(5).crossfadein(1)
c0nfluks
  • 53
  • 5
  • 1
    Why does it need to be global? To back up a bit, what exactly are you trying to do? – MattDMo Jul 29 '22 at 16:11
  • I'm trying to concatenate moviepy clips automatically. Each clips are created from a timestamps.txt file where each line represents a clip. I want each clip to be created on the fly... so basically a variable creates itself when needed. The whole point of my project is so that the final video is created automatically from the timestamps. I've edited OP with some code for each variable that would be created. – c0nfluks Jul 29 '22 at 16:31
  • You can establish the variable prior to the loop. In your code example, the final print of `variable_1` and `variable_2` will print whatever that variable is set to after the loop has completed. – Marcel Wilson Jul 29 '22 at 16:38
  • No, that won't work for what I need. – c0nfluks Jul 29 '22 at 17:45
  • 1
    Do you actually need to keep track of all the clips *at the same time* in order to get the result? Or can you just edit and concatenate each clip *to the output, as you determine it*? In the latter case, you can just reuse a variable that names "the clip currently being modified", inside your loop. If you really need separate values, please see the linked duplicate, and store them in a list or dictionary. – Karl Knechtel Jul 30 '22 at 02:12
  • Please remember that a variable is **just** a name for something. The actual **thing** that you are naming is much more interesting, in general. – Karl Knechtel Jul 30 '22 at 02:13

0 Answers0