Search code examples
pythonpython-3.xzelle-graphics

Cutting the codes in the program and making it neater


I'm having a hard time cutting the code and making it into a loop so that it would make the code of the program, neater.

Although my code works as it suppose to be, I think there is a right way of creating it, adding a for loop rather than writing all of these codes, I know there is an easy way to do this, I just couldn't figure how to do it properly. I know I'm suppose to create a for loop.

squares

from graphics import *

def main():
    win = GraphWin("Squares", 500, 500)
    
    
    rect = Rectangle(Point(0,500), Point(500,0))
    rect.setFill("Red")
    rect.draw(win)
    
    rect2 = Rectangle(Point(20,480), Point(480,20))
    rect2.setFill("white")
    rect2.draw(win)
    
    rect3 = Rectangle(Point(40,460), Point(460,40))
    rect3.setFill("red")
    rect3.draw(win)
    
    rect4 = Rectangle(Point(60,440), Point(440,60))
    rect4.setFill("white")
    rect4.draw(win)
    
    rect5 = Rectangle(Point(80,420), Point(420,80))
    rect5.setFill("red")
    rect5.draw(win)
    
    rect6 = Rectangle(Point(100,400), Point(400,100))
    rect6.setFill("white")
    rect6.draw(win)
    
    rect7 = Rectangle(Point(120,380), Point(380,120))
    rect7.setFill("red")
    rect7.draw(win)
    
    rect8 = Rectangle(Point(140,360), Point(360,140))
    rect8.setFill("white")
    rect8.draw(win)
    
    rect9 = Rectangle(Point(160,340), Point(340,160))
    rect9.setFill("red")
    rect9.draw(win)
    
    rect10 = Rectangle(Point(180,320), Point(320,180))
    rect10.setFill("white")
    rect10.draw(win)
    
    rect11 = Rectangle(Point(200,300), Point(300,200))
    rect11.setFill("red")
    rect11.draw(win)
    
    rect12 = Rectangle(Point(220,280), Point(280,220))
    rect12.setFill("white")
    rect12.draw(win)

The results shows squares into some sort of a patchwork

enter image description here


Solution

  • Try the following:

    from graphics import *
    
    def main():
        win = GraphWin("Squares", 500, 500)
    
        # create all rects
        rects = [Rectangle(Point(0 + 20*i,500 - 20*i), Point(500 - 20*i, 0 + 20*i)) for i in range(12)]
    
        # draw all rects
        for idx, rect in enumerate(rects):
            rect.fill("red" if idx % 2 == 0 else "white")
            rect.draw(win)