首页 > 解决方案 > 我想知道如何制作while循环?

问题描述

def check():
    a = 0
    b = 10

    while a <= b:
        print(a, b)
        while a <= b:
            b -=1
            print(a, b)
        a += 1

结果是:

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

我期待下面的结果,我应该如何编辑它?

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

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

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

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

直到....10

标签: pythonwhile-loop

解决方案


您忘记了恢复起始值。并且可能想要第三个变量。为了清楚起见,添加了一些额外的变量,这样您就可以尝试跟踪您的 while 循环发生了什么。

def check():
        a = 0
        limit = 10
        b_initial = 10
        b = b_initial
        while(a<=limit): #We run this from a= 0 until a=limit
            #b=b_initial Alternative location to reset b to initial value of b
            while(b>=-1): #You want to decrease b until -1 for all values of a
                print(a,b)
                b-=1 # decreasing b
            a+=1 #once the inner while loop is finished increase a by 1
            b= b_initial # reset b to 10.

推荐阅读