首页 > 解决方案 > 我如何解决海龟,Python中的奇数问题

问题描述

height = input("Enter the height: ")
height = int(height)
width = input("Enter the width: ")
width = int(width)

import turtle

width = width - 1

turtle.speed(1)

turtle.penup()

for y in range(height // 2):
    for x in range(width):
        turtle.dot()
        turtle.forward(20)
        turtle.dot()
    turtle.right(90)
    turtle.forward(20)
    turtle.right(90)
    for x in range(width):
        turtle.dot()
        turtle.forward(20)
        turtle.dot()
    turtle.left(90)
    turtle.forward(20)
    turtle.left(90)
turtle.exitonclick()

在此处输入图像描述

我想在 python 图形龟中打印点。对于我的宽度,它作为我的输入给出。但是对于高度,如果数字是偶数,我会得到准确的输出,但如果数字是奇数,我会得到高度 - 1。我知道我的代码、逻辑效率不高且不准确。我是一个自学者(仅限书籍)。

标签: pythonpython-3.xturtle-graphics

解决方案


与其修补嵌套循环,不如简化它们:

import turtle

height = int(input("Enter the height: "))
width = int(input("Enter the width: "))

turtle.speed('slowest')
turtle.penup()

angle = 90

for _ in range(height):
    for _ in range(width - 1):
        turtle.dot()
        turtle.forward(20)

    turtle.dot()

    turtle.right(angle)
    turtle.forward(20)
    turtle.right(angle)

    angle *= -1

turtle.hideturtle()
turtle.exitonclick()

推荐阅读