简体   繁体   中英

Python nested while loop, different output in c++

I am trying to learn python and some basic nested loops algorithm.

Supposed output should be: x1, x2, x3, 1, 2, 3, x1, x2, x3 ......

flag = 0
x = 0
y = 0
while(True):   
    
    while(flag == 0):
        x += 1;
        print("x", end= "")
        print(x)
        time.sleep(1)
        if (x >= 3):
            flag = 0
            break;
    y += 1
    print(y)
    time.sleep(1)
    if (y >= 3):
        flag = 0
        x = 0
        y = 0
        

What I get: x1, x2, x3, 1, x4, 2, x5, 3, x1, x2, x3, 1, 2, 3 ...

I tried doing the same code to c++ and I get correct output. Did I overlooked something in my code like proper indentions or my code is just wrong? Thanks.

The problem is that flag is always 0 . You need to set it something else after you've done your x work.

    if (x >= 3):
        flag = 1
        break

But then we wouldn't increment variables in a while if something can be iterated with a for instead.

import time

while True:    
    for x in range(1,4):
        print(f"x{x}")
        time.sleep(1)

    for y in range(1,4):
        print(f"{y}")
        time.sleep(1)

Iterating a range object manages the x and y values for you.

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