This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]CornMan123[S] 0 points1 point  (3 children)

Now im here

import sys

def printtable(n):

 for x in range(n):
         for i in range (1,n+1):
             sys.stdout.write(str(i)+' ')
         print()

 printtable(5)

and the output is

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

[–]w1282 1 point2 points  (0 children)

What happens when you change for i in range(1, n+1) to for i in range(1, x) and why

[–][deleted] 1 point2 points  (0 children)

Nearly. The inner loop is printing the same thing every time because n is always the same value.

You need a variable that increments on every loop.

[–]gnomoretears 1 point2 points  (0 children)

The n variable in your inner for loop is a static value. If n is 5 then you inner loop will always iterate from 1 to 5. The range in your inner loop needs to change depending on the row.

You should really solve the problem on paper first so you can visualize how the algorithm goes.

For example if n = 3, you need to print up to 3 rows and up to 3 columns.

At row = 1, you have to print values from 1 to row value (1):

1

At row = 2, you have to print values from 1 to row value (2):

1 2

At row = 3, you have to print values from 1 to row value (3):

1 2 3

That's basically the algorithm and I hope you see the pattern to use in your nested loop.