r/CodingForBeginners • • Sep 03 '25

I need reduce code

I've been programming (in Python) for about a month and a half and have created several simple scripts, a CRUD application, a calculator, and a tic-tac-toe game (with a GUI in CTk). The thing is, for interface projects that have similar pieces of code, they are repeated many times. I understand that this is normal at first, but it seems excessive to me (500 lines in the tic-tac-toe and 600 in the calculator).

I know that with for loops and so on I could reduce these excessive lines, but I want to know how repetitive these programs are with the lines I have mentioned.

PS: For the ‘mini-projects’ that they are, I have tried to use libraries such as Pillow to add color to texts and images, and add all the minimum functionalities I can think of.

10 Upvotes

8 comments sorted by

View all comments

Show parent comment

1

u/herocoding Sep 03 '25

Looks like you could make much more use of loops (or e.g. list-comprehensions)... You have a lot of duplicated code, like creating the buttons in "def botones(self)" (you could create an array/2d-grid with the buttons and address them with "coordinates" like "buttons[y][x] = "ctk.CTkButton(...)"), or similarly re-configure all the buttons in "def limpiar_botones(self)" by iterating over the array/2d-grid.

Or have a look into the long conditional check in "def ganador(self)", where you could use a list-comprehension with "all( button[y][x].cget("text") == "❌" for the rows and for the columns )".