python - 基于用户输入的 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()
解决方案
我发现初级程序员要么编写太多代码,要么编写太少代码。就您的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
推荐阅读
- file - 如何使用 Rust 截断或减少文件末尾的内容?
- windows - 在 Windows 操作系统中打开 Google Chrome 浏览器时创建多个实例
- python - 是否可以使用多线程使 OpenOpc 读取更快的 OPC 项目?
- vba - 在 VBA 中更改汉字的字体
- python-3.x - 有没有什么方法可以计算python中随机森林回归(连续输出)预测的置信度分数?
- python-3.x - 从数组中声明变量名称,然后将每个变量分配为 pandas 数据框
- laravel - 浏览器上的 lsapp.test 不提供索引页面,而是 localhost/lsapp/public/ 提供主页
- java - 如何从 ParseUser 子类中查询字符串列表
- python-3.x - 为什么我使用 Insert 关键字放入 List 的每个值都有一个数据类型 String
- jquery - JQuery dataTable 标头修复问题