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

问题描述 投票:-1回答:1
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!")
python turtle-graphics
1个回答
1
投票

写时:

if shape == square():

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

您对所有形状都进行了此操作,因此最终绘制了所有形状。

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

if shape == "square":

您也不应在形状函数的调用周围使用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!")
© www.soinside.com 2019 - 2024. All rights reserved.