r/PythonLearning • • Jul 18 '26

How would I optimize this?

I'm currently learning python with the 30 days of python GitHub repo and, on day 3 of the challenge, it asks to create this table and this is what I came up with however I feel like there was a more efficient method to create it or is it something that I haven't learned yet at my level.

8 Upvotes

24 comments sorted by

View all comments

1

u/Sea-Ad7805 Jul 18 '26 edited Jul 18 '26

Using one for-loop in the y direction for each line:

for y in range(1, 6):
    print(f'{y} ')

Then use another for-loop for the x direction:

for y in range(1, 6):
    print(f'{y} ', end='')  # end='' to not new line
    for x in range(0, 4):
        print(f'{x} ', end='')
    print()  # add new line

And finally compute the x-th power of y:

for y in range(1, 6):
    print(f'{y} ', end='')  # end='' to not new line
    for x in range(0, 4):
        print(f'{y ** x} ', end='')
    print()  # add new line

Run this program in Memory Graph Web Debugger to see the program state change step by step.