首页 > 解决方案 > 基于用户输入的 Python Turtle 问题绘图

问题描述

我的问题是我的 Tower 变量的高度根本没有打印出来,我觉得如果它打印了它就行不通。我不明白为什么这不起作用请帮忙。

我的代码:

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()

标签: pythonturtle-graphics

解决方案


我发现初级程序员要么编写太多代码,要么编写太少代码。就您的tower()函数而言,代码太少了。您还可以将x变量用于两个不同的目的——摆脱使用单字母变量名的习惯。不需要您的“请输入塔数:”问题,因为输入的塔高度数会为您提供相同的值。这是您的第一个逻辑错误:

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

We do want to split that input string on comma, but we want to turn it into a list of number instead of strings. One way:

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

The next issue surfaces in tower():

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

This reuse of x masks our heights, what you really wanted was something like:

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

But we don't need to use indexing, we can simply walk x itself. A rework of your code with the above fixes, some tower drawing, and some style changes:

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

OUTPUT

enter image description here


推荐阅读