def magic_square(n):
n = int(n)
magicSquare=[]
for i in range(n):
l=[]
for j in range(n):
l.append(0)
magicSquare.append(l)
print("Before processing the program..")
for i in range(n):
for j in range(n):
print(magicSquare[i][j], end=" ")
print(" ")
i = n//2
j = n-1
count = 1
num = n*n
while count <= num:
if i == -1 and j == n: # wen (p-1,q+1) becomes -1 and n we have to switch to 0,2
i = 0
j = 2
else:
if i == -1:
i = n-1
if j == n:
j = 0
if magicSquare[i][j] != 0: # increment row by one and decrement column by 2
i = i+1
j = j-2
continue
else:
magicSquare[i][j] = count
count += 1
i = i-1
j = j+1
print("Before processing the program..")
for i in range(n):
for j in range(n):
print(magicSquare[i][j], end=" ")
print(" ")
m = int(input("Enter the Square Matrix dimension"))
magic_square(m)
I am trying to create a magic square program using python on pycharm .. I keep getting this error and i dont know how to fix it .. if anyone knows please help me fixing the error..Remember to give i/p anything other than 3 .. Thank you in advance
it takes input only for 3 This is the o/p i am getting
Before processing the program..
Traceback (most recent call last):
File "location", line 48, in <module>
magic_square(m)
File "location", line 30, in magic_square
if magicSquare[i][j] != 0: # increment row by one and decrement column by 2
IndexError: list index out of range
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
Process finished with exit code 1
I was trying to solve magic square problem in python
As I guess, the issue is input
n, will always be a valid odd number. However, the code does not handle the case whennis even or not an integer. Then, you can add some input validation at the beginning of the function to validate ifnis a valid odd or integer.Try this,