一个让用户从五个形状中选择一个形状的程序,但它同时绘制所有相同的形状,我做错了什么?

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

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

from turtle import*
def square():
  for i in range(4):
    forward(30)
    right(90)

def triangle():
  for i in range(3):
    forward(50)
    left(120)

def pentagon():
  for i in range(5):
    forward(30)
    right(72)

def hexagon():
  for i in range(6):
    forward(30)
    right(60)

def star():
  for i in range(5):
    forward(50)
    right(144)

def pause():
  penup()
  forward(70)
  pendown()

shape = (input("Type one of these shapes square, triangle, pentagon, hexagon, star"))



if shape == square():
    print (square())

elif shape == triangle():
    print (triangle())


elif shape == pentagon():
    print (pentagon())

elif shape == hexagon():
    print (hexagon())

elif shape == star():
    print (star())
else:
  print("Shape is not valid, please input a valid one!")

Tags: inrightforinputdefrangestarforward
1条回答
网友
1楼 · 发布于 2024-05-20 01:51:55

当你写作时:

if shape == square():

它调用square函数来绘制正方形。然后将用户的输入与返回值进行比较。由于函数不返回任何内容,因此比较失败

你对所有的形状都这样做,所以它最终绘制了所有的形状

您应该将用户的输入与字符串进行比较,而不是调用函数

if shape == "square":

您也不应该在调用shape函数时使用print(),因为它们不会返回任何应该打印的内容。所以它应该是这样的:

if shape == "square":
    square()
elif shape == "triangle":
    triangle()
...
else:
    print("shape is not valid, please input a valid one!")

与所有的if语句不同,更聪明的方法是使用从形状名称映射到函数的字典:

shape_map = {"square": square, "triangle": triangle, "pentagon": pentagon, ...}
if shape in shape_map:
    shape_map[shape]()
else:
    print("shape is not valid, please input a valid one!")

相关问题 更多 >