python - 我想知道如何制作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
解决方案
您忘记了恢复起始值。并且可能想要第三个变量。为了清楚起见,添加了一些额外的变量,这样您就可以尝试跟踪您的 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.
推荐阅读
- mysql - 如何计算两个直接行之间的最大差值?
- typescript - 使用接口的通用键作为值
- prolog - 如何在 prolog 中实现更统一的回溯?
- python - 尝试计算 np.zeros 时出现内存错误
- apache - 限制来自特定域解决方案的访问/媒体资源请求,而不是通过 .htaccess 直接访问
- php - 通过在 laravel 视图中传递数组索引来显示国家名称
- rust - Rust:错误,类型不匹配。找到 std::result::Result
- javascript - 不能在 NgModule 中声明模块,因为它不是当前编译 Angular 的一部分
- python - 为什么相同的代码在其他 Flask BluePrint 中会出现导入错误
- c# - C# 从不同的表单调用文本框