python - Python中的For / While循环三角形不起作用
问题描述
处理我的第二个三角形,但它没有给我使用 while 嵌套循环所需的结果,我应该有以下输出。
使用 for 循环:
0
01
012
0123
01234
012345
使用 while 循环:
5
45
345
2345
12345
012345
代码:
print('Using for loop')
print()
M = 6 #constant
cnt = 1
for i in range(0,M):
for j in range(0,cnt):
if(j<M):
print(j,'',end='')
else:
print('',end='')
cnt+=1
print()
print()
print('Using While loop')
print()
cnt = 6
while(cnt != -1):
for j in range(0,cnt-1):
if(j<cnt+1):
print(j,'',end='')
else:
print(j)
cnt -=1
print()
print()
我目前的结果是..
使用 for 循环
0
01
012
0123
01234
012345
使用 while 循环
012345
01234
0123
012
01
0
解决方案
你有很多语法错误使用这个
print('Using for loop')
print()
M = 6 #constant
cnt = 1
for i in range(0,M):
for j in range(0,cnt):
if(j<M):
print(j,'',end='')
cnt+=1
print()
print('\nUsing While loop\n')
cnt = 0
while(cnt != M):
for j in range(0,M-(cnt+1)):
print(' ','',end='')
for j in range(0,cnt+1):
print(M-(cnt+1-j),'',end='')
cnt +=1
print()
print()
推荐阅读
- django - 如何组合日期字段和时间字段以存储在 Django api 发布请求中的日期时间字段中?
- c++ - 在 C++ 中使重载的成员访问运算符返回一个临时值
- javascript - 折叠 rowGroup 闪亮
- jquery - 具有不同内容的 Jquery 对话框
- android - 为 Android 运行 dx 或 d8 工具时出错
- powerbi - Power BI - 显示前一个工作日的数据 - 不包括周末
- php - 如何在数据表复选框中更新多个使用 php/ajax?
- java - 使用 JSoup 调用 JSP 函数
- asp.net-core - 如何改进工厂方法以便能够以正确的方式注册依赖项
- javascript - 将公共假日纳入工作日功能