星号三角形 Python(带输入)

Asterisk Triangle Python (with input)

我正在 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

从这一点来看,我很迷茫,所以任何帮助将不胜感激。

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

def asterisk():
    ast = "*"
    i = 1
    lines = int(input("How many asterisks do you want? "))
    space = " "
    for i in range(0, lines+1):
        print (lines * space, ast*i)
        lines -= 1
        i += 1

正如 Jeff L. 提到的,您没有调用您的函数,因此您确实打印了一个 space、一颗星,然后是 myLen 的新值。

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

查看下面的代码:

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);

这对你有用。

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)

您的解决方案存在一些问题,我不确定您要做什么 there.You 创建了一个名为 printRow 的函数,但您没有使用它。尝试在调试时干 运行 代码。 遵循纸上的一切。例如,写下每次迭代的值变量以及每次迭代的输出。它将帮助您找出哪里出错了。 祝一切顺利!