我开始尝试让我的代码从0-9返回9行。
0123456789
0123456789
0123456789
0123456789
就这样等等。相反,我从输出中得到了这个
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
[6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
[8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
我的代码
def countdown(count):
while (count <= 9):
print ([count]*10)
count += 1
countdown(0)
我知道括号是从哪里来的,我试着摆脱它们,但是每次我尝试不使用它们运行时,[count]
,我的代码就乱七八糟了。我知道我读过关于将数据传输到str的文章,但是尽管我尝试过,但我还没有弄清楚这一点。
问题1是如何解决这个问题,这样我就可以让它按照我最初的要求去做。
问题2或多或少是我在想,我是否可以做些什么来摆脱[ ]
,从我当前的输出,这样我就不会再犯同样的错误了。
发布于 2015-09-13 02:04:21
[]
来自[count]
,它是一个包含一个元素count
的列表。你不需要它在这里。
要打印9
行的0
-9
,建议嵌套循环,可能还有range
。不要硬编码9
和10
到代码中,将其作为函数的参数传递。下面是一段有一些问题的代码:
def countdown(count):
for i in range(count):
for j in range(count):
print(j)
countdown(10)
输出的9
时间为0
- 9
,但每个数字都在自己的行中。--我没有给你工作代码,这里有一个提示:循环使用print
手册,如何在不开始新行的情况下打印一些东西?
发布于 2015-09-13 02:11:25
您应该执行如下所示的操作:
def countdown(count):
while (count <= 9):
print (''.join(str(x) for x in range(0,10)))
count += 1
countdown(0)
另外,somevalue * 10将创建一个包含10个元素的列表,其中每个元素都是==。为。例如:* 10是0,0,0,0,0,0,0,0,0
1,1 *2是1,1,1,1
发布于 2015-09-13 07:15:51
您将希望使用循环。根据您想要打印一个int或string的情况,有两种方法我可以考虑这样做,同时尽可能地对答案进行文字处理。
如果您只需要将数字打印到屏幕上,那么字符串就足够了。
def countdown():
for i in range(0,9): #Iterate for 9 lines
x="" #Using string x
for j in range(0,10): #Iterate through numbers 0-9 which is actually ten digits
x += str(j) #convert the int j to a string and add it to string x
print(x)
如果您试图输出int,则在打印之前将字符串转换为int a。
def countdown():
for i in range(0,9): #Iterate for 9 lines
x="" #Using string x
for j in range(0,10): #Iterate through numbers 0-9 which is actually ten digits
x += str(j) #convert the int j to a string and add it to string x
y = int(x) #convert the string x to int y
print(y)
在任何一种情况下,您的shell都应该打印如下:
>>> countdown()
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
您试图使用一个列表,它可以实现类似的结果,但不是您所要求的结果。
https://stackoverflow.com/questions/32545543
复制相似问题