2016-10-28 78 views
1

我正在做一個python 3的初學者課程,並且必須形成一個星號三角形,輸出如下。 Asterisk triangle formatAsterisk三角形Python(附輸入)

我嘗試到目前爲止看起來如下:

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

從這一點上,我完全迷失了方向,所以任何幫助,將不勝感激。

+1

你在倒數第二行調用'print',而不是'printRow'函數。 – Jeff

回答

0

傑夫L. mentionned你是不是叫你的功能,讓您確實打印一個空間,一個明星,然後是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); 
+0

非常感謝,我明白我現在去哪裏錯了! – blockoblock

1

這是一個非常基本的一個,可以得到改善,但你可以借鑑一下:

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

有一對夫婦與您的解決方案的問題,我不完全知道你試圖做there.You了一個叫printRow功能,但你不使用它。嘗試在調試時執行代碼的空運行。 按照紙上的一切。例如,在每次迭代中寫出什麼值變量會具有什麼值,以及每次迭代時輸出的值是多少。它會幫助你弄清楚你出錯的地方。 一切順利!