Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following is a working example. With comments in the code so you can better understand each step.

# import required to use randint
import random

# holds the last number to be randomly generated
previous_number = None
while True: # 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 6
    if previous_number == 6 and num == 6:
        # if the above is true then break out the loop
        break
    # store the latest number and start the loop again
    previous_number = num 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...