[英]Nested Loop in Python Not Working
I would like to have this output: 我想要这个输出:
* * *
2 2 2
4 4 4
6 6 6
8 8 8
I cannot get it and I've tried many ways, but my code doesn't seem to work. 我无法获得它,我已经尝试了很多方法,但是我的代码似乎无法正常工作。 Here is my current code:
这是我当前的代码:
for row in range(3):
print ("*", end = " ")
print ()
for col in range(2,9,2):
print (row, end = " ")
print ()
print()
What do I do? 我该怎么办?
I don't see why you are using end
in your print statements. 我看不出您为什么在打印语句中使用
end
。 Keep in mind that you must print line by line. 请记住,您必须逐行打印。 There is no way to print column by column.
无法逐列打印。
print('* * *')
for i in range(2, 9, 2):
print('{0} {0} {0}'.format(i))
For further explanation about the {0}
s, look up the format
method for strings: https://docs.python.org/2/library/string.html#format-string-syntax 有关
{0}
的进一步说明,请查找字符串的format
方法: https : //docs.python.org/2/library/string.html#format-string-syntax
print('* * *')
for col in range(2,9,2):
print (*[col]*3, sep=' ')
To be more clear. 更加清楚。
>>> a = 2
>>> [a]
[2]
>>> [a]*3
[2, 2, 2]
>>> print(*[a]*3, sep=' ') # equal to print(a, a, a, sep=' ')
2 2 2
For a start, you only have one row that contains * * *
which can be printed at the very top, outside of any loops: 首先,您只有一行包含
* * *
行,该行可以在任何循环之外的最顶部打印:
print('* * *')
Next, you would need to start your loop from values 2
(inclusive) and 9
(exclusive) in steps of 2
: 接下来,你需要从价值观开始你的循环
2
(含)和9
中的步骤(独家) 2
:
for col in range(2,9,2):
You don't need to use any end
keyword here, so just printing the row multiple times is sufficient: 您无需在此处使用任何
end
关键字,因此只需多次打印该行即可:
print('{0} {0} {0}'.format(i))
So the final block of code looks like: 因此,最后的代码块如下所示:
print('* * *')
for row in range(2,9,2):
print('{0} {0} {0}'.format(row))
You don't need to add another print()
, print
already ends with a newline anyway. 您无需添加其他
print()
,无论如何, print
已经以换行符结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.