打印9行从0到9不起作用

时间:2015-09-13 01:48:12

标签: python python-3.x

我开始尝试让我的代码从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或多或少地想知道我是否可以做些什么来摆脱[ ],从我当前的输出,以便我不再犯同样的错误。

3 个答案:

答案 0 :(得分:1)

你应该做如下所示的事情:

def countdown(count):
    while (count <= 9):
        print (''.join(str(x) for x in range(0,10)))
        count += 1

countdown(0)

此外,[somevalue] * 10将创建一个包含10个元素的列表,其中每个元素== somevalue。 对于。例如。 [0] * 10是[0,0,0,0,0,0,0,0,0,0]

[1,1] * 2是[1,1,1,1]

答案 1 :(得分:0)

[]来自[count],这是一个包含一个元素count的列表。你在这里不需要它。

打印9 - 0的{​​{1}}行,表示嵌套循环,可能还有9。 不要在代码中硬编码range9,将其作为函数的参数传递。这是一段有一些问题的代码:

10

输出具有def countdown(count): for i in range(count): for j in range(count): print(j) countdown(10) - 9的{​​{1}}次,但每个数字都在其自己的行中。 我没有给你工作代码,这里有一个提示:循环使用0的手册,如何在不开始新行的情况下打印一些内容?

答案 2 :(得分:0)

您将要使用for循环。根据你是否想要打印出一个int或字符串,我可以通过两种方式来思考这个问题,同时尽可能地了解答案。

如果您只需要将数字打印到屏幕上,则字符串就足够了。

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。

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

您试图使用一个列表,该列表可以获得类似的结果但不是您要求的。