Bit of python help
I've tried to get this to work, but it just freezes. It should display a pyramid, but all it does is.. halts.
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 col开发者_运维知识库our[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
- Well first the color-input loop does not do what you want it to do.
The 'and' in if ((colour[0] and colour[1] and colour[2]) in valid_colours):
compares their string values to each other, where any non-empty string evaluates as True. The expression evaluates to colour[2], assuming it is the last non-empty string, you can prove this with: print (colour[0] and colour[1] and colour[2])
Change to: if (colour[0] in valid_colours and colour[1] in valid_colours and colour[2] in valid_colours):
- Your main rectangle-drawing loop: The intent of the following code is to iterate from 1..width (inclusively)
:
barloopWidth = 0
while loopWidth < width:
loopWidth = loopWidth + 1
do stuff using (loopWidth + 1)
so replace it with: for loopWidth in range(1,width+1):
The loop iterating c and colour through 6 loops of white,red can be rewritten using '*' (the sequence replication operator):
for colour in ['white','red']*6:
So your main loop becomes:
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
- As to why it hangs on your pyramid coordinates loop, debug it yourself using print:
print 'Drawing rectangle from (%d,%d) to (%d,%d)'% (p[0],p1[0],p[1],p1[1])
You might find it helpful for testing to isolate that code info a function draw_pyramid(), away from get_colors().
精彩评论