Home > Blockchain >  assign variables automatically when the loop
assign variables automatically when the loop

Time:04-01

p_dil_1, p_dil_2, p_dil_3, p_dil_4 ..... are variables I have already made.

tg1 = p_dil_1
tg2 = p_dil_2
n_dil = 0

while True : 
    n_dil  = 1
    # some movement here
    
    if n_dil == 10 :
        break
    if n_dil <= 10 : 
        tg1 = p_dil_2
        tg2 = p_dil_3
        continue 

The original purpose is

For the first loop, tg1=p_dil_1, tg2=p_dil_2

For the second loop, tg1=p_dil_2, tg2=p_dil_3

...

For the tenth loop, tg1=p_dil_10, tg2=p_dil_11

and end the loop

How can I make the loop simple?

CodePudding user response:

Here is a way to make things a bit simpler and cleaner.

var listOfValues = [p_dil_1, p_dil_2, ..., p_dil_11] // etc.
for n_dil = 0; n_dil <= 10; n_dil  = 1 {
    // Some Movement
    tg1 = listOfValues[n_dil]; tg2= listOfValues[n_dil   1];
}

Hope this helps.

CodePudding user response:

You can't assign variables dynamically. Use a list and use a variable to reference the position in the list.

list = [a, b, c, d, e, f]
index = 0
while index < 5:
  var1 = list[index]
  var2 = list[index   1]
  # use var, var2
  index = index   1

CodePudding user response:

Your best approach would be to use dictionaries. Please also check your logic as when n_dil = 10 the last, if statement will never be executed as the loop, breaks first.

p_dil_dict = {1: "foo", ..., 2: "bar"}
tg1 = p_dil_dict["1"]
tg2 = p_dil_dict["2"]

for n_dil in range(1, 10): # n_dil = 1, 2..., 8, 9
    # do something

    tg1 = p_dil_dict[n_dil]
    tg2 = p_dil_dict[n_dil]

Notice how a for loop can be started at 1 if necessary (although I'd recommend starting at 0). Also the for loop means you don't need to break a while loop or set and increment n_dil.

CodePudding user response:

You can store your p_dil_1, p_dil_2... etc in a list, lets say - p_dil[]. You can initialize tg1 and tg2 with p_dil[0] and p_dil[1]. Then start your loop with n_dil = 2 and note that the variable tg1 takes the value of tg2 from the previous iteration.

p_dil = [p_dil_1, p_dil_2, ....]
tg1 = p_dil[0]
tg2 = p_dil[1]
n_dil = 2
while n_dil <= 10:
    tg1 = tg2
    tg2 = p_dil[n_dil]
    n_dil  = 1

CodePudding user response:

What about using for loop?

tgs = [p_dil_3, p_dil_4, ..., p_dil_11]
tg1, tg2 = p_dil_1, p_dil_2

for new_dil in range(tgs):
    # some movement....
    tg1 = tg2
    tg2 = new_dil
  • Related