Use input () within a for cycle (Python)

2

I am trying to create a matrix in which the user enters the number of rows, columns and each term:

colum=int(input('Cantidad de columnas: '))
fil=int(input('Cantidad de filas: '))
matriz=[[str(input('[',i,',',j,']-esimo termino: ')) for i in range(colum)] for j in range(fil)]

However, after entering the number of rows and columns I get the error:

TypeError: input expected at most 1 arguments, got 5  

I have tried to rewrite the code in different ways and it keeps throwing me the same error. My question is, can not I place an input () inside a for loop? Or in any case, what has been my mistake here?

    
asked by Stefano Gobbi 30.03.2017 в 16:15
source

1 answer

1

The problem is that you are using input as if you were passing arguments to the function print . print accepts an indeterminate number of arguments, input only accepts one of type str . The solution is to unite your chains so that they form a single chain, a single argument. To format the string you pass to input , it is best to use the method format of the chains:

colum=int(input('Cantidad de columnas: '))
fil=int(input('Cantidad de filas: '))
matriz=[[str(input('[{},{}]-esimo termino: '.format(i, j))) for i in range(colum)] for j in range(fil)]

With what we get:

  

Number of columns: 3
  Number of rows: 2
  [0,0] -th term: 1
  [1,0] -th term: 2
  [2.0] -th term: 3
  [0,1] -th term: 4
  [1,1] -th term: 5
  [2,1] -th term: 6
  > > > matrix
  [['1', '2', '3'], ['4', '5', '6']]

There is another alternative way that is to concatenate chains but the recommended form is the previous one, besides being simpler:

matriz=[[str(input('['+str(i)+','+str(j)+'-esimo termino: ')) for i in range(colum)] for j in range(fil)]
    
answered by 30.03.2017 / 16:33
source