0

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.

S.B
17.1k12 gold badges38 silver badges74 bronze badges
asked Jul 25, 2021 at 12:40
1
  • for exapmle n=5 , i start 1 to 5 and multiple it Commented Jul 25, 2021 at 12:47

3 Answers 3

2

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
answered Jul 25, 2021 at 12:59
Sign up to request clarification or add additional context in comments.

Comments

0

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
answered Jul 25, 2021 at 12:53

Comments

0
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
answered Jul 25, 2021 at 12:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.