[英]Can anyone help me figure out the parsing error in this code?
代码是:
def printMultiples(n): i = 1 while (i <= 10): print(n*i, end = ' ') i += 1 n = 1 while (i<= 3): printMultiples(n) n += 1
输出为:
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30
而应该是这样的:
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30
在while (i <= 10):
循环之外,在printMultiples
的末尾添加一个空print
。
您的问题是您没有在每个倍数列表之后打印新行。 您可以通过将printMultiples
函数的末尾放在循环之外来解决此问题
print()
为了使列对齐,您将需要完全改变您的方法。 当前, printMultiples()
无法知道在每个数字之后放置多少空格,因为它不知道在外部while
循环中将调用多少次。
您可能会做的是:
str()
函数将对此有用 如果只对列式输出感兴趣,而不对精确的间距感兴趣,那么一种更简单的方法是在每个数字之后打印足够的空间,以容纳您希望输出的最大数字。 这样您可能会得到:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
(请注意,即使您不需要所有三个空格,也要在前三列中的每个数字后面留三个空格。)
更改现有代码以实现此目的将更加容易。 有关详细信息,请参见格式化字符串语法 。
如果您已经知道希望将数字填充为3的宽度,则可以使用合适的(以及更多Python风格的)printMultiples
def printMultiples(n):
txt = "".join(["{0: <3d}".format(n*i) for i in range(1, 11)])
print(txt)
更好的办法是允许宽度改变。 然后,您可以传递您喜欢的宽度,例如,您期望的最大数字的宽度
def printMultiples(n, width=3):
txt = "".join(["{0: <{1}d}".format(n*i, width) for i in range(1, 11)])
print(txt)
width = len(str(4 * 10)) + 1
for i in range(1, 4):
printMultiples(i, width )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.