Update a variable based on different ranges in a loop in python

Viewed 83

I need to have a periodic update of a variable within a loop where I need to set the variable value (X_state) according to these ranges. For example, if I have a loop that starts from 1 to 200, and I need to set my variable, X_state from 0 to 1, whenever the start of the range represents a multiple of 60 and the end is equal to start+5. So, what I'm not sure about is how to keep updating this X_state starting from 60 till 65, then starting from 120 until 125, 180 until 185 in this example.

It works with me only in the first range which is from [60-65]

periodic = 60
for i in range(200):
print(i)
if (i%periodic==0)or (i>=periodic and i<=periodic+5):
    x_state = 1
else:
    x_state= 0
print("x_state= ",x_state)
2 Answers

Your if statement only checks for periodic (60), not multiples of periodic. This should achieve your desired effect:

periodic = 60
for i in range(200):
  print(i)
  x_state = 0
  if 0 <= i % periodic <= 5:
      x_state = 1
  print("x_state= ",x_state)

Here I can account for any multiples of periodic by checking the number modulo periodic.

periodic = 60
for i in range(200):
  if (i % periodic >= 0) and (i % periodic <= 5):
    x_state = 1
  else:
    x_state = 0
  print(i, "x_state = ", x_state)
Related