I am working on a practice program where I design a function that takes a table and prints it out right justified. My code isn't the best, I am still a beginner so I don't know all the ways to make my code shorter just yet. For the actual printing part of the function, I was having trouble using the sep=''
parameter in the print function. I was able to code around it but I'd like to try and understand where I went wrong that it didn't work.
Here's my code (it currently only works on a list that is 3x3):
table = [['Koda','Lucy','Sokka'],
['Red','Black','Grey'],
['Dog','Dog','Cat']]
lengths = [] # must make global variable so value will be added with each iteration of for loop
for d in range(len(table)): # 3 times
for a in range(len(table[d])):
x,y,z = table[d][0:3]
if len(x) > len(y):
if len(x) > len(z):
longest = len(x) # order here does matter. cannot assign function as variable
break
elif len(x) < len(z):
longest = len(z)
break
else:
longest = len(x)
break
elif len(x) < len(y):
if len(y) > len(z):
longest = len(y)
break
elif len(y) < len(z):
longest = len(z)
break
else:
longest = len(y)
break
else:
if len(x) == len(z):
longest = len(x)
break
elif len(x) < len(z):
longest = len(z)
break
else:
longest = len(x)
break
lengths.append(longest)
for i in range(len(table)):
a = table[0][i].rjust(lengths[0])
b = table[1][i].rjust(lengths[1])
c = table[2][i].rjust(lengths[2])
print(a+' '+b+' '+c)
The very last print line, I tried to type as:
print(a+b+c,sep=' ')
But it printed:
Koda RedDog
Where the a variable was justified and a seeming space added but no space was added between b and c.
Is my syntax slightly off or does it have to do with the flow using indexes instead of straight integers? I was able to find a way around it but I think understand why it didn't work, especially if its something I did wrong would be extremely helpful.
Also, if anyone had any hints to help make my code work for a list of any size, I will graciously accept them.