You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python代码以正确打印居中三角形图案

逻辑错误定位

你的代码存在两处核心问题,直接导致输出不符合预期:

  • 元素计数逻辑完全错误:前置空格的while循环执行结束后,spaces变量已经被递减为0,此时stars = maxRows - spaces的计算结果恒等于maxRows,这就是每行都打印和总行数相等数量星号的根本原因。实际上当前行需要打印的元素数量应该和当前行号currentRow相等。
  • 元素输出规则错误:打印元素时没有在相邻元素之间添加空格,输出的是连续拼接的实心字符,和要求的“元素间带空格”效果不符。
修复方案

修正上述两个逻辑点即可,你可以选择更简洁的字符串写法,也可以保留原有的嵌套while循环结构:

简洁写法(推荐)

用Python字符串内置方法替代嵌套循环,逻辑简洁不容易出现边界错误:

currentRow = 1
maxRows = int(input("Enter the maximum number of rows: "))
while currentRow <= maxRows:
    # 打印行首的居中对齐空格
    print(" " * (maxRows - currentRow), end="")
    # 生成当前行元素,自动在元素间插入空格,不会产生末尾多余空格
    print(" ".join(["1"] * currentRow))
    currentRow += 1

保留原while循环结构的写法

只修改元素计数和打印逻辑,和你最初的代码结构保持一致:

currentRow = 1
maxRows = int(input("Enter the maximum number of rows: "))
while currentRow <= maxRows:
    spaces = maxRows - currentRow
    while spaces > 0:
        print(" ", end='')
        spaces -= 1
    # 修正:当前行元素数等于当前行号
    stars = currentRow
    while stars > 0:
        # 最后一个元素后不打印空格,避免对齐偏移
        if stars == 1:
            print("1", end='')
        else:
            print("1 ", end='')
        stars -= 1
    print()
    currentRow += 1

两种写法输入行数为4时,输出都完全匹配预期:

1
  1 1
 1 1 1
1 1 1 1

如果需要打印星号图案,只需要把代码中打印的"1"替换为"*"即可。


内容的提问来源于stack exchange,提问作者user19409398

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 04:36:14