How do you reach a certain value for two variables at the same time while iterating?

Viewed 41

I have 2 variables that contain the amount of steps I want to do in each direction.

    # could be any values (including being the same amount)
    x_steps = 300
    y_steps = 200

Now I want to draw a line slowly by moving both the current x-coordinate and y-coordinate. The important thing is, that I want to finish both directions at the same time, so it looks like a straight line. This means, that in some iterations I need to do multiple steps for (in this case) x.

    for x in range(y_steps):
        # do step in y direction
        # do step in x direction
        if certain_condition:
            # do another step in x direction

I'm having trouble coming up with such a condition, how do I achieve this?

1 Answers

You could do this by keeping track of the number of steps and using those numbers in the condition:

i, j = 0, 0
for x in range(y_steps):
    # do step in y direction
    j += 1
    # do step in x direction
    i += 1
    if i/j < x_steps/y_steps:
        # do another step in x direction
        i += 1

To simplify this, you can use x (maybe rather call it y, as it runs through the y steps) directly instead of j, or use a while loop.

Related