簡體   English   中英

用新行打印python

[英]printing in new lines python

我做了這個小東西,我需要的輸出是這樣的:

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

但是我這樣得到輸出:

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

你可以幫幫我嗎? 這是程序。

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)

添加“ \\ 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

您不需要該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”是一個整數,而不是列表( 不要使用“ 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)

您可能可以從函數本身打印星形,而不是返回它。 打印將自動添加新行。 希望有幫助!

我對代碼進行了一些更改,但是您的問題是您發送的是int而不是包含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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM