[英]Python nested while loop, different output in c++
I am trying to learn python and some basic nested loops algorithm.我正在尝试学习 python 和一些基本的嵌套循环算法。
Supposed output should be: x1, x2, x3, 1, 2, 3, x1, x2, x3 ......
假设输出应该是: 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 ...
我得到的是: 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.我尝试对 C++ 执行相同的代码,并得到正确的输出。 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
.问题是flag
总是0
。 You need to set it something else after you've done your x
work.完成x
工作后,您需要对其进行其他设置。
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.但是如果某些东西可以用for
迭代,我们就不会在一段while
增加变量。
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.迭代范围对象可以为您管理x
和y
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.