Python turtle用户inpu

2024-05-20 01:51:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一些代码,当用户输入一个图形时,乌龟会绘制它,这是我目前所拥有的,但它只是一直绘制一个五角大楼

    import turtle
turtle.shape('turtle')

def triangle():
    for i in range(3):
        turtle.forward(50)
        turtle.right(360/3)


def square():
    for i in range(4):
        turtle.forward(50)
        turtle.right(360/4)

def pentagon():
    for i in range(5):
        turtle.forward(50)
        turtle.right(360/5)


answer = input('pick a shape.. triangle, square or pentagon')
if answer ==('triangle'):
    triangle()

elif answer == ('square'):
    square()

elif answer == ('pentagon'):
    pentagon()

else:
    print ('wrong input')

Tags: answerinrightforinputdef绘制range
2条回答

嘿,你可以试试下面的代码:

import turtle
def triangle():
    for i in range(3):
        turtle.forward(50)
        turtle.right(360/3)


def square():
    for i in range(4):
        turtle.forward(50)
        turtle.right(360/4)

def pentagon():
    for i in range(5):
        turtle.forward(50)
        turtle.right(360/5)

turtle.shape('turtle')
answer = raw_input('pick a shape.. triangle, square or pentagon: ')

print(answer)

if answer ==('triangle'):
    triangle()

elif answer == ('square'):
    square()

elif answer == ('pentagon'):
    pentagon()

else:
    print ('wrong input')

我会把你的数据和你的代码分开一点,然后这样做:

from turtle import Turtle, Screen

DISTANCE = 100

def polygon(turtle, sides):
    for _ in range(sides):
        turtle.forward(DISTANCE)
        turtle.right(360 / sides)

shapes = { \
    'triangle': lambda turtle: polygon(turtle, 3), \
    'square': lambda turtle: polygon(turtle, 4), \
    'pentagon': lambda turtle: polygon(turtle, 5), \
}

shape = input('Pick a shape: ' + ", ".join(shapes) + ': ')

if shape in shapes:

    yertle = Turtle(shape='turtle')

    shapes[shape](yertle)

    screen = Screen()
    screen.exitonclick()

else:
    print('Bad input!')

如果您对lambda语句感到不舒服,可以简单地执行以下操作:

def triangle(turtle):
    polygon(turtle, 3)
...
shapes = { \
    'triangle': triangle,
    ...
}

对于要实现的每个形状。

相关问题 更多 >