如何修复Python打印菱形代码输出多余风筝形图案的bug
Python菱形打印程序多余输出Bug修复方案
Bug定位
程序打印完标准菱形后额外输出风筝形图案的核心原因有两处:
- 负责打印菱形下半部分的
while currentRow <= maxRows循环中,错误嵌套了一层while leftRows > 0的内层循环。菱形下半部分每1个currentRow值仅对应1行输出,该内层循环会导致每次外层循环迭代时,额外打印从leftRows值递减到1的所有行,最终产生冗余输出。 - 代码未初始化循环变量
currentRow,直接运行存在未定义变量报错风险,本地可运行属于交互环境残留了历史变量赋值的偶发情况。
修复方法
- 移除第二个外层循环中多余的
while leftRows > 0嵌套层级,每轮外层循环仅计算一次当前行的空格、星号数量,打印单行星号后直接递增currentRow即可。 - 在所有循环开始前初始化
currentRow = 1。
修复后完整代码
limitRows = int(input("Enter the maximum number of rows: ")) maxRows = limitRows + (limitRows - 1) currentRow = 1 # 补全循环变量初始化 while currentRow <= limitRows: spaces = limitRows - currentRow while spaces > 0: print(" ", end='') spaces -= 1 stars = currentRow while stars > 0: print("*", end=' ') stars -= 1 print() currentRow += 1 while currentRow <= maxRows: # 移除多余的leftRows内层循环,每轮currentRow对应打印一行 leftRows = maxRows - currentRow + 1 spaces = limitRows - leftRows while spaces > 0: print(" ", end='') spaces -= 1 stars = leftRows while stars > 0: print("*", end=' ') stars -= 1 print() currentRow += 1
修复后验证效果
输入行数为4时的标准输出如下,无多余尾随行:
* * * * * * * * * * * * * * * *
内容的提问来源于stack exchange,提问作者user19409398
相关产品推荐
相关产品推荐

