Click here to Skip to main content
15,918,516 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, I am new to Python. I am new to Python and need some assistance. I am trying to make a 4x4 magic square with a two-dimensional array. I am trying to make this code so I can add the two dimensional array as a function? I learn best by example so if anyone could show me directly with code I would appreciate it.

What I have tried:

def main():

    magicsquare = [[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]
    notmagicsquare = [[10, 7, 4, 5], [2, 1, 0, 8], [8, 4, 6, 1], [4, 4, 5, 1]]

    for r in range(rows):
        for c in range(columns):

    for r in range(rows):
        for c in range(columns):

Updated 25-Jun-22 4:35am

The problem with "I learn best by example" is that when you copy and paste code from the internet without trying to understand it, you don't learn anything - as you have shown in your code sample.

That won't run, because neither rows nor columns are defined.
I'd suggest that as someone who "learns best by example" you go back to the place you got the code from, and look at the whole code: then try to learn how it works before you try using it as a basis for your own task.

While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.

And to be honest, nobody learns best by example: you learn by doing, not looking. You can watch the Tour de France as much as you like, but that won't teach you to ride a bike yourself. Only sitting on a bike (with or without trainer wheels) and trying to ride will teach your body how to balance it and the subtle movements which you move to maintain that balance.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
Share this answer
Try this
magicsquare = [[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]
for row in magicsquare:

Now go to The Python Tutorial — Python 3.10.5 documentation[^], where you will find answers to all your questions.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900