2016-10-11 115 views
-3
I want to print : 
    1 
    12 
    123 
1234 

,我曾嘗試:如何使用循環創建直角三角形?

num=int(input("number")) 
space=int(num) 
count=1 
while count<num: 
    if count==1: 
    print(" "*space,count) 
    count=count+1 
    space=space-1 
    while count>=2: 
     for n in range(2,num): 
     print(" "*space,list(range(1,n)) 
     space=space-1 

但它不工作。 如何打印指定的結果? 感謝

+0

請將代碼放在帖子中,而不是它的圖像。 – Phylogenesis

+0

請修正代碼的縮進情況,以便它能夠精確表示您在編輯器中的代碼。 – idjaw

+0

我剛剛上傳了代碼。 – triumpyhyale

回答

0
print(" "*space,list(range(1,n)) 

計數在這條線的括號內。其中一個沒有關閉,它必須按照你的意圖工作。

另請注意,您的while循環將永不停止運行。

作爲一個一般的經驗法則,只要你知道你應該到底有多少次做的事情,你應該使用for循環,而不是一個while循環

讓我們嘗試使用for循環來重寫你的代碼:

num=int(input("number")) 
output = "" 
for n in range(1,num+1): 
    output = ''.join([output, str(n)]) 
    space = ' ' * (num - len(output)) 
    print(space, output, sep='') 

我所做的除for循環以外唯一真正的實質性變化是將輸出視爲字符串而不是數字列表。

+0

形狀可以改善嗎?謝謝 ! – triumpyhyale

+0

@triumpyhyale以什麼方式?如果輸出時看起來很奇怪,可能是您用來顯示輸出的字體 –