Hi everyone I have this code :
n=int(input())
for i in range(1,n+1):
for j in range(1,n+1):
print(i*j)
the output is this:
1
2
3
4
5
2
4
6
8
10
3
6
...
but I want to get output like this :
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
I Don't know what to do for print like this.
-
for exapmle n=5 , i start 1 to 5 and multiple ittara bah– tara bah2021年07月25日 12:47:28 +00:00Commented Jul 25, 2021 at 12:47
3 Answers 3
Pythons print function automatically print a newline each time the function is called. but you can set what it will print at the end of the line, with adding end='' for nothing or for space end=' '.
In you case you can try this bellow:
n=int(input())
for i in range(1,n+1):
for j in range(1,n+1):
print(i*j, end = ' ')
print()
And the print at the end will print a newline after each completion of the first loop.
Finally you output will be like this:
5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Comments
Python 2.x:
n=int(input())
for i in range(1, n + 1):
val = '';
for j in range(1, n + 1):
sep = '' if(j == 5) else ' '
val += (str) (i * j) + sep
print(val)
Python 3.x:
n=int(input())
for i in range(1, n + 1):
for j in range(1, n + 1):
print(i*j, end = ' ')
print()
Output:
5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Comments
n = int(input())
for i in range(1,n + 1):
count = 0
for j in range(1, n + 1):
print(i * j, end = ' ')
count += 1
if count % (n) == 0:
count = 0
print()
I initialized a counter variable and if count mod n is 0, then I assigned the counter to 0 and print a new line. This is the output
5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25