0

I am using jupyter notebook. I want to print a simple integer matrix in the general form, i.e., I eant the output to be like this: a[0][0] = 1 a[0][1] = 2 a[1][0] = 3 a[1][1] = 4

Here's my program:

column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print ("a[",i,"][",j,"] =",a[i][j],"\t",),
    print ("\n")

But I get the output as:

Enter the number of columns: 2
Enter the number of rows: 2
 Enter the elements: 1
 Enter the elements: 2
 Enter the elements: 3
 Enter the elements: 4
a[ 0 ][ 0 ] = 1     
a[ 0 ][ 1 ] = 2     


a[ 1 ][ 0 ] = 3     
a[ 1 ][ 1 ] = 4 

The print(), function in the loop goes to a new line even though I have put a comma after it. Please help me get the desired output format. Thank you.

AKX
  • 152,115
  • 15
  • 115
  • 172
Shg
  • 11
  • 1
  • 3
  • 3
    Is this python 2 or python 3? – Aran-Fey Jun 05 '17 at 10:52
  • @Rawing since the parentheses don't show up in the output we must conclude that it's python 3 (or `print_function` is used in python 2). – Leon Jun 05 '17 at 10:56
  • 4
    The `print()` *function* (from Python 3) is not used in the same way as the `print` *statement* in Python 2. In the *function* use `end=""` parameter to suppress the newline ending. – cdarke Jun 05 '17 at 10:57
  • Duplicate of https://stackoverflow.com/questions/4499073/printing-without-newline-print-a-prints-a-space-how-to-remove ? – Till Jun 05 '17 at 11:01
  • Thanks a lot, It works now :) – Shg Jun 05 '17 at 11:04

2 Answers2

0

this will not print new line

print(something,end="")

and your code

column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print("a[%d][%d] = %d "%(i,j,a[i][j]),end="")
Arvind
  • 1,006
  • 10
  • 16
0

the other answers are good, but a much more readable code would be this:

some_string = ''
for i in range (0, row):
    for j in range (0, column):
        some_string += "a[{}][{}]= {} ".format(i,j,a[i][j])
print(some_string)
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62