## talat.zaitoun

``````def matrix(mat, num):
for i in mat:
for j in i:
print(j * num)
``````

So I'm trying to make a code that multiplies a matrix by a number, my code above is not working and i think the reason is the for statements could be wrong, so what i tried to do in my code is say for i in mat which should read each row and for j in i, it should read each value in a row. Then it supposed to multiply each value in the row my a num. Any help is appreciated thank you.

## Schol-R-LEA 1,087

I ran the code, and while it didn't print in the manner you probably would like, it does indeed multiply the matrix by a scalar. What problem are you experiencing with it?

First off, the name `matrix()` for this isn't really appropriate; it's matrix multiplication, whereas the name `matrix()` makes it sound like a class c'tor.

On that note, I would say that writing a `Matrix` class would be a good idea, given that you'll almost certainly want to do more than just multiply by a scalar and print out the results.

I would recommend separating the process of printing the matrix from that of multiplying it; this will, among other things, allow you to keep a copy of the new value, rather than simply display it.

## talat.zaitoun

I apologize I just realized I wasn't clear, I'm supposed to return the value as a matrix multiplied by a number but it only works when I use print if I change it to return it will multiply the matrix as a whole and not each value for ex it will do this 3*f = f f f, this is the problem I apologize again for the unclarity

## Schol-R-LEA 1,087

You need to step through the matrix, just as you are now, but at the same time you need to generate a new matrix and assign the multiplied values to its elements.

``````def scalar_mult(matrix, scalar):
matrix_prime = list()
for i in m:
vector = list()
for j in i:
vector.append(j * scalar)
matrix_prime.append(vector)
return matrix_prime
``````

## talat.zaitoun

Thank you, it worked but is it possible to do it without using append? Or is this the only way cause I have not learned append yet?

## Schol-R-LEA 1,087

Off the top of my head, the two other approaches which come to mind - using the `enumerate()` operator, and using a list comprehension - would both involve things which you probably haven't used before, either. There may be others here who can think of still other approaches, I guess.