【问题标题】:printing in new lines python在新行中打印python
【发布时间】:2014-03-01 17:42:02
【问题描述】:
我做了这个小东西,我需要输出,例如,像这样:
****
*******
**
****
但我是这样得到输出的:
************
你能帮帮我吗?这是程序。
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)
【问题讨论】:
标签:
python
function
python-3.x
newline
lines
【解决方案1】:
添加“\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
【解决方案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)
【解决方案3】:
您可能可以从函数本身打印星星而不是返回它。 print 将自动添加一个新行。希望对您有所帮助!
【解决方案4】:
我对代码做了一些修改,
但是您的问题是您发送的是 int 而不是带有 ints 的列表:
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)