[英]Python 3.X: Call Outside Variable In Nested For Loop
I've nested one for
loop inside of another.我将一个
for
循环嵌套在另一个循环中。 The first loop simply iterates over the second loop five times;第一个循环简单地迭代第二个循环五次; the second loop iterates over the same simple block of code five times.
第二个循环在同一个简单的代码块上迭代了五次。
In total, these loops should perform the same job twenty-five times.总的来说,这些循环应该执行相同的工作 25 次。
x = 0
for y in range(0, 5,):
for z in range(0, 5,):
print(str(int(x + 1)) + ". Hello")
I expected the output to be:我预计输出是:
1. Hello.
2. Hello.
3. Hello.
4. Hello.
5. Hello.
Twenty-five times, with each proceeding line increasing the number's value by one.二十五次,每行增加数字的值一。
Instead, the output was:相反,输出是:
1. Hello
This output repeated itself twenty-five times.这个输出重复了 25 次。 How do I fix this problem and receive the output I want?
如何解决此问题并接收我想要的输出?
You aren't updating the value for x
as you loop through.您在循环时不会更新
x
的值。
Try this:尝试这个:
x = 0
for y in range(0, 5,):
for z in range(0, 5,):
x+=1
print(str(x) + ". Hello")
You are almost there.你快到了。 Just add one extra line
只需多加一行
x = 0
for y in range(0, 5,):
for z in range(0, 5,):
print(str(int(x + 1)) + ". Hello")
x += 1
you can also use this :你也可以使用这个:
i = 0
for y in range(0, 5):
for z in range(0, 5):
i = i+1
print(str(i) + "." " Hello.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.