python - Python 中的倒金字塔

标签 python python-3.x

我想用下面给出的代码得到一个倒金字塔。类似的代码适用于直立金字塔,但这些调整似乎不适用于倒金字塔。

尝试对语句进行大量调整,但没有成功。

    def pym(rows):
      result = ''
      for i in range(rows):
        row = ''
        row += '#' * (i-1)
        row += '*' * (2 * (rows-i) + 1)
        row += '#' * (i-1)
        result += row + '\n'
      return result
    print (pym(4))

预期输出

*******
#*****#
##***##
###*###

最佳答案

for 循环条件稍微不正确,循环应该更正为 for i in range(1,rows+1): 而不是 for i in range(rows):,然后你的代码就可以完美运行了。

def pym(rows):
    result = ''

    #Corrected the range
    for i in range(1,rows+1):
        row = ''
        row += '#' * (i-1)
        row += '*' * (2 * (rows-i) + 1)
        row += '#' * (i-1)
        result += row + '\n'
    return result

print (pym(4))

然后是输出

*******
#*****#
##***##
###*###

如您所见,从 i=0 而不是 i=1 开始会导致行变量出现问题,例如在 for 循环的前两个表达式中使用 i = 0row 如下所示

In [21]: row = ''                                                                                                                                                                                       

In [22]: row += '#' * -1                                                                                                                                                                                

In [23]: row                                                                                                                                                                                            
Out[23]: ''

此外,由于您只迭代到 rows-1,因此您最终也没有得到最终的金字塔。

关于python - Python 中的倒金字塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56141883/

相关文章:

python - 将元组字符串转换为元组

python - 计算pandas面板数据集中并发实体的数量

python - 我可以将 wtforms DateTimeField 设置为也只接受日期值吗?

python - 如何跨重叠摄像机检测物体

python - 装饰器 "object is not callable"

python - Python 3.7 中的 Pickle 重大变化

python - 在 Python 中查看是否有来自管道的输入?

python-3.x - SSL : WRONG_VERSION_NUMBER

python - 如何在Python中的主线程继续工作的情况下在单独的线程中实现阻塞监听功能

python - 在方法中使用 Python property()