Re: Program matx.py

Alan Gauld via Tutor <[email protected]>
Newsgroups gmane.comp.python.tutor
Message-ID <[email protected]>
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



_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.