2014-03-01 98 views
0

我做了這個小東西,我需要的輸出是,例如,像這樣:印刷在新線蟒蛇

**** 
******* 
** 
**** 

,但我得到的輸出是這樣的:

************ 

你能幫我嗎?這是該計劃。

import math 
def MakingGraphic(number): 
    list = [number] 
    graphic = number * '*' 
    return(graphic) 


list = 0 
howmany = int(input("How many numbers will you write?")) 
for i in range(0, howmany, 1): 
    number = int(input("Write a number ")) 
    list = list + number 
result = MakingGraphic(list) 
print(result) 

回答

2

你並不需要一個MakingGraphic,只是用一個列表來存儲的「*」的字符串:

In [14]: howmany = int(input("How many numbers will you write?")) 
    ...: lines=[] 
    ...: for i in range(howmany): 
    ...:  number = int(input("Write a number ")) 
    ...:  lines.append('*'*number) 
    ...: print('\n'.join(lines)) 

你的代碼的問題是,變量「列表」是一個整數,而不是一個列表(不要使用「list」作爲變量名稱,因爲它會影響python內置類型/函數list,請改用一些名稱,如lst)。

如果你想嘗試函數調用,您可以更改您的代碼:

import math 
def MakingGraphic(lst): 
    graphic = '\n'.join(number * '*' for number in lst) 
    return graphic 


lst = [] 
howmany = int(input("How many numbers will you write?")) 
for i in range(0, howmany, 1): 
    number = int(input("Write a number ")) 
    lst.append(number) 

result = MakingGraphic(lst) 
print(result) 
3

添加「\ n」返回到下一行。 例如result = MakingGraphic(list) + "\n"

爲什麼順便使用列表?

import math 
def MakingGraphic(number): 
    return number * '*' 

result = '' 
howmany = int(input("How many numbers will you write?")) 
for i in range(0, howmany, 1): 
    number = int(input("Write a number ")) 
    result += MakeingGraphic(number) + "\n" 
print result 
1

你或許可以從函數本身打印星星,而不是返回它。打印將自動添加一個新行。希望有所幫助!

0

我做在代碼中的一些變化, 但你的問題,你是發送INT不跟整數列表:

import math 
def MakingGraphic(number): 
    graphic = '' 
    for n in list:# loop to the list 
    graphic += n * '*' + '\n' # the \n adds a line feed 
    return(graphic) 

list = [] # list 
howmany = int(input("How many numbers will you write?")) 
for i in range(0, howmany, 1): 
    number = int(input("Write a number ")) 
    list.append(number) # add the number to the list 
result = MakingGraphic(list) 
print (result)