星号三角形Python(带输入)

时间:2016-10-28 15:40:40

标签: python asterisk

我正在做一个关于python 3的初学者课程,并且必须形成一个星号三角形,输出如下所示。Asterisk triangle format

到目前为止,我的尝试如下:

def printRow(c, length) :

    line = c * length
    print(line)
myLen = 0
stars ="*"
n = myLen-1
spaces = (' '*n)
myLen = int(input("Enter number to make triangle: "))


if myLen<=0 :
    print("The value you entered is too small to display a triangle")
elif myLen>=40 :
    print("the value you entered is too big to display on a shell window")
while myLen>0 :
    print(spaces, stars, myLen)
    myLen = myLen-1

This is what it outputs in the shell

从这一点开始我很失落,所以任何帮助都会受到赞赏。

3 个答案:

答案 0 :(得分:1)

这是一个非常基本的,可以改进,但你可以从中学习:

{{1}}

答案 1 :(得分:1)

这对你有用。

def printer(n):
    space=" "
    asterisk="*"
    i=1
    while(n>0):
        print((n*space)+(asterisk*i))
        n=n-1
        i=i+1

n=input("Enter a number ")
printer(n)

您的解决方案存在一些问题,我不确定您在那里尝试做什么。您创建了一个名为printRow的函数,但您没有使用它。尝试在调试时执行干代码。 跟随纸上的一切。例如,编写每个迭代将具有的值变量以及每次迭代时的输出。它可以帮助您找出出错的地方。 一切顺利!

答案 2 :(得分:0)

正如Jeff L.提到的那样,你没有调用你的函数,所以你确实打印了一个空格,一个星,然后是myLen的新值。

关于实际问题,让我们尝试从右到左逐行绘制。 首先计算空间的数量,以及行的星数。打印出来,转到下一行。

见下面的代码:

space = ' ';
star = '*';

size = int(input("Enter number to make triangle: \n"))

def printRow(current_row, max_row) :
    line = space * (max_row - current_row) + star * current_row;
    print(line)

if size<=0 :
    print("The value you entered is too small to display a triangle")
elif size>=40 :
    print("the value you entered is too big to display on a shell window")


for i in range(1, size + 1) :
    printRow(i, size);