-3

Simple question - I want a loop that counts up and returns to 0 when it reaches a certain number.

Tried something like:

while i < 7:
    i += 1
    if i == 7
        i -= 1   #(or change i in any other way - you get the idea)

My Python actually crashed when I tried the above.

EDIT: Yes, the if condition is never met - it still crashes when I change it to if i == 6 though.

martineau
  • 119,623
  • 25
  • 170
  • 301
Flying Thunder
  • 890
  • 2
  • 11
  • 37

3 Answers3

1
while i < 7:
      i += 1
      if i == 7:
         i = 0

The problem is the i-=1 line. Your code works as i counts up to 6, but when it reaches 6, it is incremented to 7, and then subtracted down to 6 again. Your current sequence is 0,1,2,3,4,5,6,6,6,6,...

SawyerWelden
  • 100
  • 1
  • 9
0

If you want to count up to 7 then count down to 0 here is what you can try:

i = 0
add = True
while True:
    if add:
        i += 1
    else:
        i -= 1

    if i in [0, 7]:
        add = not add
Lorenzo Vincenzi
  • 1,153
  • 1
  • 9
  • 26
0

This is your corrected code,

i = 0
while i < 7:
    i += 1
    if i == 6:
           i = 0

It reaches 0 on reaching 6. Lot's of syntax Error fixed.

Nikhil.Nixel
  • 555
  • 2
  • 11
  • 25