有点python的帮助

时间:2010-05-12 13:59:35

标签: python

我试图让它工作,但它只是冻结。 它应该显示金字塔,但它所做的只是......停止。

from graphics import * 

valid_colours = ['red', 'blue', 'yellow', 'green']
colour = ['', '', '']

while True:
    colour[0] = raw_input("Enter your first colour: ")
    colour[1] = raw_input("Enter your second colour: ")
    colour[2] = raw_input("Enter your third colour: ")
    if ((colour[0] and colour[1] and colour[2]) in valid_colours):
        break 

while True:
    width = raw_input("Enter a width between 2-7: ")
    if width.isdigit(): 
        if (int(width) <= 7 and int(width) >= 2):
            break 

width = int(width)

win = GraphWin("My Mini Project ", 1000, 1000) # 1000 \ 20 = 50
win.setCoords(0 , 0 , 20, 20)
p1 = [0, 2]

while width > 0:
    p = [1, 3]
    loopWidth = 0
    while loopWidth < width:
        loopWidth = loopWidth + 1

        c = 0
        while c <= 10:
            c = c + 1
            if c % 2: 
                colour = "white"
            else:
                colour = "red"

            rectangle = Rectangle(Point(p[0],p1[0]), Point(p[1], p1[1]))
            rectangle.setFill(colour)
            rectangle.setOutline("black")
            rectangle.draw(win)

            p[0] = p[0] + 0.2
            p1[0] = p1[0] + 0.2

        p[0] = p[0] - 2
        p1[0] = p1[0] - 2

        p[0] = p[0] + 2
        p[1] = p[1] + 2

    width = width - 1
    p1[0] = p1[0] + 2
    p1[1] = p1[1] + 2

1 个答案:

答案 0 :(得分:1)

  • 首先,颜色输入循环不能达到您想要的效果。

if ((colour[0] and colour[1] and colour[2]) in valid_colours):中的'和' 将它们的字符串值相互比较,其中任何非空字符串的计算结果为True。表达式求值为color [2],假设它是最后一个非空字符串,你可以用print (colour[0] and colour[1] and colour[2])

来证明这一点。

更改为:if (colour[0] in valid_colours and colour[1] in valid_colours and colour[2] in valid_colours):

  • 您的主要矩形绘图循环: 以下代码的目的是从1..width(包含)
  • 进行迭代

barloopWidth = 0
while loopWidth < width:
    loopWidth = loopWidth + 1
    do stuff using (loopWidth + 1)

所以用以下代替:     for loopWidth in range(1,width + 1):

  • 循环迭代c和颜色通过6个白色,红色循环可以使用'*'(序列复制操作符)重写:

    表示['white','red'] * 6中的颜色:

所以你的主循环变为:

while width > 0:
    p = [1, 3]

    for loopWidth in range(1,width+1):
        for colour in ['white','red']*6:

            #Draw your rectangles

            p[0]  += 2
            p1[0] += 2

        p[0] -= 2
        p1[0] -= 2

        p[0] = p[0] + 2
        p[1] = p[1] + 2

    width = width - 1
    p1[0] += 2
    p1[1] += 2
  • 至于它挂在金字塔坐标循环上的原因,请使用print自行调试: print 'Drawing rectangle from (%d,%d) to (%d,%d)'% (p[0],p1[0],p[1],p1[1])

您可能会发现测试将该代码信息与函数draw_pyramid()隔离,远离get_colors()有用。

相关问题