简体   繁体   English

python FOR循环在一个函数中连续2个循环只运行第一个循环

[英]python FOR loop 2 consecutive loops in one function only 1st loop runs

I have two FOR loops that can run fine individually.我有两个可以单独运行的 FOR 循环。 When i try to run them together in the same function only the first loop is run.当我尝试在同一个函数中一起运行它们时,只运行第一个循环。

My code looks like this:我的代码如下所示:

def loop_code():
        for x in range(10):
            x -= 1 
            print(x)
        for y in range(10):
            y += 1 
            print(y)

loop_code()

output:输出:

-1
0
1
2
3
4
5
6
7
8

I need to output this instead:我需要输出这个:

-1
0
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
9
10

Thank you for your help!感谢您的帮助!

That is not an elegant way to do the things.这不是一种优雅的做事方式。 Modifying your index variable while in a for loop breaks the interest of said for loop.在 for 循环中修改索引变量会破坏上述 for 循环的兴趣。 If you want you loop to go from -1 to 8 use:如果您希望循环从 -1 到 8,请使用:

for index in range(-1,9)

Then if you want your second for loop to have its index go from 1 to 10 use:然后,如果您希望第二个 for 循环的索引从 1 变为 10,请使用:

for other_index in range(1,11)

Your question could use some clarification.你的问题可能需要一些澄清。 I'm helping you on getting the output you want but there might be some XY Problem going on here.我正在帮助你获得你想要的输出,但这里可能会出现一些XY 问题 Is there a particular reason you wanted to modify your index in the for-loop?您是否有特殊原因想要在 for 循环中修改索引?

check out the definiton of range() function.查看 range() 函数的定义。 a change as simple as range(12) would do.range(12)这样简单的改变就可以了。 (think about it, you want 12 itarations!) (想想看,你想要 12 次迭代!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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