[Tutor] Program matx.py

Alan Gauld alan.gauld at yahoo.co.uk
Mon Dec 25 14:49:47 EST 2023


On 24/12/2023 20:41, Ethan Rosenberg wrote:
> Help Desk -
> 
> Thank you for the excellent help you give to Python programmers.
> 
> Do I have to be registered to submit a question?
> 
> This program is supposed to insert i*j into the cells of a 2x2 matrix.  I
> receive a syntax error.
> 
> #matx.py
> #program to add i*j to cells of 2x2 matrix
> 
> mat = [][]

This is the syntax error. You need to nest the lists.


mat = [[]]

ie create a list of lists.
But...

> for i in range(0,1):

this will only yield a value for i of 0
since range(0,1) is just 0.
Better would be to say:

for i in range(2):

>     for j in range(0,1):

Same here

>         mat[i][j] = i*j

This will fail because the second list is empty
so [j] doesn't exist.

You need to create a list of initialised values.
Lets say None:

mat = [[None,None][None,None]]

Or more generically:

mat = [[None]*2 for size in range(2)]

Now your loops should work.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos





More information about the Tutor mailing list