基于用户输入的Python Turtle问题绘图

时间:2018-06-11 02:38:32

标签: python turtle-graphics

我的问题是我的塔变量的高度根本不打印,我觉得如果它确实不行的话。我无法理解为什么这不起作用请帮助。

我的代码:

import turtle
bob = turtle.Turtle()
turtle.setup(width = 400, height = 300)
turtle.bgcolor("orange")
n = int(input("Please enter number of towers: "))
h = (input("Please enter height of towers : "))
x = str(h.split(","))
def ocean():
    bob.setpos(-200, 0)
    bob.color("midnightblue", "midnightblue")
    bob.begin_fill()
    for x in range(1, 3):
        bob.forward(400)
        bob.right(90)
        bob.forward(150)
        bob.right(90)
    bob.end_fill()

def tower():
    bob.right(90)
    for x in range (0,n):
        bob.forward(x)


ocean()
tower()

1 个答案:

答案 0 :(得分:0)

我发现初级程序员要么编写太多代码,要么太少代码。对于tower()函数,它的太少代码。您还将x变量用于两个不同的目的 - 不再使用单字母变量名称。您输入的塔高数量可以获得相同的值“请输入塔数:”问题。这是您的第一个逻辑错误:

x = str(h.split(","))

我们确实希望将该输入字符串拆分为逗号,但我们希望将其转换为数字列表而不是字符串。一种方式:

x = map(int, h.split(","))

下一期问题将出现在tower()

for x in range (0,n):
    bob.forward(x)

x的这种重用掩盖了我们的高度,你真正想要的是:

for idx in range(n):
    bob.forward(x[idx])
    ...

但我们不需要使用索引,我们可以简单地 x本身。使用上述修复,一些塔式绘图和一些样式更改对代码进行返工:

from turtle import Turtle, Screen

WIDTH, HEIGHT = 400, 300

def ocean():
    bob.setpos(-WIDTH/2, 0)
    bob.color("midnightblue")
    bob.begin_fill()

    for _ in range(2):
        bob.forward(WIDTH)
        bob.right(90)
        bob.forward(HEIGHT/2)
        bob.right(90)

    bob.end_fill()

def tower():
    for height in heights:
        bob.left(90)
        bob.forward(height)
        bob.right(90)
        bob.forward(50)
        bob.right(90)
        bob.forward(height)
        bob.left(90)

heights_string = input("Please enter height of towers: ")
heights = map(int, heights_string.split(","))

screen = Screen()
screen.setup(width=WIDTH, height=HEIGHT)
screen.bgcolor("orange")

bob = Turtle()

ocean()
tower()

bob.hideturtle()

screen.mainloop()

<强> USAGE

> python3 test.py
Please enter height of towers: 100,30,140,60,90,20,45

<强>输出

enter image description here