在Python中绘制三角形时遇到问题,求助

1 投票
2 回答
605 浏览
提问于 2025-04-17 23:21

我正在用Python做一个三角形的作业,这是我计算机科学课的任务,但我有点搞不清楚。
输出应该是这样的:

Select your height. > 5

    *
   **
  ***
 ****
*****

但是我得到的结果是这样的:

Select your height. > 5

    *
    **
    ***
    *****
    ******

这是我的源代码。

抱歉代码有点长,也有点乱,我现在用的是vim这个文本编辑器,而且我对它还不太熟悉。
如果这个问题不太好,我真的很抱歉……我查过Python的文档页面,试过.ljust()和.rjust(),但似乎对我没什么帮助。非常感谢你们的帮助!

# The tools we will use:
# We're just using this to make the program have a more clean, organized feel when executing it.
import time

# This will help build the triangle, along with other variables that will be described later. Spacing is necessary to help build a presentable triangle.
asterisk = "* "

# added will be used in the loop to control how long it will keep repeating the task.
added = 0

# This will multiply the amount of asterisks so that every time a line passes during the loop, it will steadily increase by one.
multiplier = 2

tab = ("""\t\t""")
nextline = ("""\n\n""")


# the finished product!

triangle = ("""""")



# THE PROCESS

print("I will ask you for a height -- any height. Once you tell me, I'll make an isosceles triangle for you.")

#time.sleep(2)

height = input("Please enter a height. > ")


heightNum = int(height)



while heightNum <= 0:

        print ("Oops, you can't insert negative numbers and zeroes. Please try another one!")
        height = input("Please enter a height. > ")
        heightNum = int(height)



while heightNum > added:

        if added == 0:
                triangle = (tab + triangle +  asterisk + nextline)
                added += 1


        else:
                starsline =(tab + asterisk * multiplier + nextline)
                triangle  = (triangle + starsline)

                added += 1
                multiplier += 1


print("Here it is! \n\n\n")
print(triangle)

print ("\n\nThis triangle is %d asterisks tall.") % heightNum                                                                                

2 个回答

0
def triangle(n):
  return '\n'.join(
      '%s%s' % (' ' * (n - i), '*' * i)
      for i in xrange(1, n + 1))

print triangle(5)

这个代码之所以能工作,是因为

'x' * n 生成了一个字符串,这个字符串是把 n 个 'x' 连在一起的。接下来的 '%s%s' % ... 这一行用这个字符串来生成一行,左边是空格,右边是星号。

'\n'.join(...) 是把一系列的内容用换行符连接起来,这样就把每一行组合成一个三角形。

for i in xrange(1, n + 1) 是用来创建一个计数器 i,它从 1 计数到 n。这里的 n + 1 是因为在 Python 中,范围是半开区间,也就是说包含起始值但不包含结束值。

0
def print_triangle(length):
    for i in range(1, length+1):
         print('{0:>{length}}'.format('*'*i, length=length))

使用方法:

>>> print_triangle(5)
    *
   **
  ***
 ****
*****

简单来说,这里用的是字符串格式化的小语言

 '{0:>{length}}'

第一个左括号对应的是第一个参数,而:表示后面会有格式说明。>的意思是要把内容靠右对齐,宽度是由另一个关键词变量提供的,也就是三角形的长度。

这些信息应该足够你完成任务,而不需要重写整个脚本。

撰写回答