[英]Can anyone help me figure out the parsing error in this code?
The code is: 代码是:
def printMultiples(n): i = 1 while (i <= 10): print(n*i, end = ' ') i += 1 n = 1 while (i<= 3): printMultiples(n) n += 1
The output is: 输出为:
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
Whereas it should be like: 而应该是这样的:
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
。
Your problem is that you are not printing a new line after each list of multiples. 您的问题是您没有在每个倍数列表之后打印新行。 You could solve this by putting at the end of your
printMultiples
function outside of the loop the line 您可以通过将
printMultiples
函数的末尾放在循环之外来解决此问题
print()
To make the columns line up, you will need to completely change your approach. 为了使列对齐,您将需要完全改变您的方法。 Currently,
printMultiples()
cannot know how many spaces to put after each number because it doesn't know how many times it will be called in the outer while
loop. 当前,
printMultiples()
无法知道在每个数字之后放置多少空格,因为它不知道在外部while
循环中将调用多少次。
What you might do is: 您可能会做的是:
str()
function will be useful for this str()
函数将对此有用 A simpler approach, if you're only interested in columnar output and not the precise spacing, would be to print each number with enough space after it to accommodate the largest number you expect to output. 如果只对列式输出感兴趣,而不对精确的间距感兴趣,那么一种更简单的方法是在每个数字之后打印足够的空间,以容纳您希望输出的最大数字。 So you might get:
这样您可能会得到:
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
(Note how there are three spaces after each number in the first three columns even though you don't need all three spaces.) (请注意,即使您不需要所有三个空格,也要在前三列中的每个数字后面留三个空格。)
Changing your existing code to do that would be easier. 更改现有代码以实现此目的将更加容易。 See Format String Syntax for details.
有关详细信息,请参见格式化字符串语法 。
If you already know you wish to pad numbers to be of width 3, then a suitable (and more pythonic) printMultiples is 如果您已经知道希望将数字填充为3的宽度,则可以使用合适的(以及更多Python风格的)printMultiples
def printMultiples(n):
txt = "".join(["{0: <3d}".format(n*i) for i in range(1, 11)])
print(txt)
Better would be to allow the width to change. 更好的办法是允许宽度改变。 And you could then pass a width you prefer as, eg, the width of the largest number you expect
然后,您可以传递您喜欢的宽度,例如,您期望的最大数字的宽度
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.