Can anyone help me figure out the parsing error in this code?
- The output of this code is quite similar but not exactly what it's supposed to be.
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
- How should this code be modified?
add an empty print
at the end of the printMultiples
, outside the while (i <= 10):
loop.
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
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.
What you might do is:
- create a two dimensional array of string representations for each multiple (without printing anything yet) - the
str()
function will be useful for this - for each column, check the length of the longest number in that column (it will always be the last one) and add one
- print each row, adding the appropriate number of spaces after each string to match the number of spaces required for that column
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
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 )
精彩评论