Home > other >  Using if condition for successive states coming across
Using if condition for successive states coming across

Time:10-12

I want to print 'double' when x equals 'ok' two times consecutively in the while loop.

My script below:

import random
import time

a = 5

while True:
    b = random.randint(0, 10)
    print(b)
    if a > b:
        x = 'ok'
        print(x)

CodePudding user response:

You need to track your state.

import random
import time

a = 5
prev = False

while True:
    b = random.randint(0, 10)
    print(b)
    if a > b:
        if prev:
            print('double')
        x = 'ok'
        prev = True
    else:
        x = 'ko'
        prev = False
  • Related