需要一些帮助尝试在Python中构建一个三角形,但我一直都错了

时间:2014-03-21 21:49:35

标签: python string python-3.x

我试图在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 :(得分:0)

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

用法:

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

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

 '{0:>{length}}'

第一个开始括号被索引到第一个参数,:表示格式规范将跟随它。 >表示通过宽度对其进行右对齐,宽度由另一个关键字变量提供,即三角形的长度。

这应该足以让你完成,而无需重写整个脚本。

答案 1 :(得分: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个字符,左边是空格,右边是星号。 / p>

'\n'.join(...)在换行符上加入generator expression,将行合并为一个三角形。

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