简体   繁体   中英

Python: Why isn't this block of code exiting after 3 iterations?

for i in range(3):
    while True:
            x = random.randint(10,50)
            y = random.randint(10,50)
            xy = x*y
            print("What's " + str(x) +" * " + str(y) + "?")
            a = input()
            if int(a) == x*y:
                  print('YOU ARE CORRECT!')
                  time.sleep(.5)
            else:
                  print("DISHONOR!  THE ANSWER IS ACTUALLY " + str(x*y) + ".")
                  time.sleep(.5)

print('next')

Why isn't the range(3) at the beginning having any effect on the code below it?

You have an infinite loop inside the loop you're asking about. Because of this, the outer loop never gets beyond the first iteration.

You need to either remove the infinite loop completely, or make it finite (by either having a condition that eventually becomes True or by using break .)

OK, so I needed to change the while True to the below, which will let the loop go 3 times.

z = 0
while z < 3: 
        z = z + 1
        x = random.randint(10,50)
        y = random.randint(10,50)
        xy = x*y
        print("What's " + str(x) +" * " + str(y) + "?")
        a = input()
        if int(a) == x*y:
              print('YOU ARE CORRECT!')
              time.sleep(.5)
        else:
              print("DISHONOR!  THE ANSWER IS ACTUALLY " + str(x*y) + ".")
              time.sleep(.5)

print('Next')

Alternatively, I could have kept my original code, and added breaks

for i in range(3):
    while True:
            x = random.randint(10,50)
            y = random.randint(10,50)
            xy = x*y
            print("What's " + str(x) +" * " + str(y) + "?")
            a = input()
            if int(a) == x*y:
                  print('YOU ARE CORRECT!')
                  time.sleep(.5)
                  break
            else:
                  print("DISHONOR!  THE ANSWER IS ACTUALLY " + str(x*y) + ".")
                  time.sleep(.5)
                  break

print('next')

Or even differently, only added a break to the correct answer or wrong answer part, then the loop would have terminated after 3 correct or 3 wrong answers respectively (vs just 3 answers, whether right or wrong).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM