How To Tell An Infinite Loop To End Once One Number Repeats Twice In A Row (in Python 3.4)
The title says it all. I have an infinite loop of randomly generated numbers from one to six that I need to end when 6 occurs twice in a row.
Solution 1:
The following is a working example. With comments in the code so you can better understand each step.
# import required to use randintimport random
# holds the last number to be randomly generated
previous_number = NonewhileTrue: # infinite loop# generates a random number between 1 and 6
num = random.randint(1, 6)
# check if the last number was 6 and current number is 6if previous_number == 6and num == 6:
# if the above is true then break out the loopbreak# store the latest number and start the loop again
previous_number = num
Solution 2:
just break
when the appropriate condition is met.
break
leaves the loop instantly.
while True:
# ...
if last_val == val == 6:
break
last_val=val # save valfor next iteration
Solution 3:
y = 0while1:
# --> "random Generator" rNumber
if rNumber == 6:
y +=1else:
y = 0if y == 2:
break
Post a Comment for "How To Tell An Infinite Loop To End Once One Number Repeats Twice In A Row (in Python 3.4)"