用新线条打印python

时间:2014-03-01 17:42:02

标签: python function python-3.x newline lines

我做了这个小东西,我需要输出,例如,像这样:

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

但我这样得到输出:

************
你可以帮帮我吗?这是该计划。

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)

4 个答案:

答案 0 :(得分: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 :(得分: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”是一个整数,而不是一个列表(使用“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)

答案 2 :(得分:1)

您可以从函数本身打印星星而不是返回它。 print会自动添加一个新行。希望有所帮助!

答案 3 :(得分:0)

我在代码中做了一些更改, 但是你的问题是你发送的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)