需要一些帮助来尝试用Python构建一个三角形,但我一直弄错了

2024-06-01 01:05:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用Python做这个三角形,作为我计算机科学课的作业,但是我搞不懂。 输出应该是这样的:

Select your height. > 5

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

但结果是这样的:

^{pr2}$

这是源代码。在

我很抱歉的长度和轻微的不规则,我目前正在使用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                                                                                

Tags: thetoyouaddedtimeisitasterisk
2条回答
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个字符,左边是空格,右边是星号。在

'\n'.join(...)在换行符上连接generator expression,将行组合成三角形。在

for i in xrange(1, n + 1)使用另一个生成器迭代行计数器i,从1到n。n + 1存在,因为python中的范围是half-open。在

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

和用法:

^{pr2}$

To break it down, this is using the string formatting mini-language

 '{0:>{length}}'

第一个左括号被索引到第一个参数,:表示后面将有格式化规范。>表示按另一个关键字变量三角形的长度提供的宽度右对齐。在

这应该足够让你完成,而不是重写你的整个脚本。在

相关问题 更多 >