从输入函数获取输入,并使用该字母运行函数

时间:2019-03-10 07:15:43

标签: python

我知道使用eval()函数是可行的,但是不能在我的程序中起作用。我不知道为什么。那么,还有另一种方法吗?这是一些代码:我正在寻找一种简单的方法,因为我是python编程的新手。真的很新...我已经尝试过eval(),但是它只会返回错误。我已经在这里呆了几个小时了,还没有在线找到答案。如果相关,我使用repl.it turtle。

import turtle

from time import sleep
ninja = turtle.Turtle()
ninja.hideturtle()
coordinate1 = ninja.xcor()
coordinate2 = ninja.ycor()
new1=''
new2=''

ninja.speed(10)
def h():
  ninja.left(90)
  ninja.forward(50)
  ninja.back(100)
  ninja.forward(50)
  ninja.right(90)
  ninja.forward(35)
  ninja.left(90)
  ninja.forward(-50)
  ninja.forward(100)
  coordinate1 = ninja.xcor()
  coordinate2 = ninja.ycor()
  new1 = coordinate1+50

  ninja.penup()
  ninja.goto(new1,0)

def i():
  ninja.forward(20)
  ninja.pendown()

  ninja.left(90)

  ninja.st()
  ninja.right(90)
  ninja.stamp()

  ninja.ht()
  ninja.penup()
  ninja.back(20)
  ninja.pendown()
  ninja.back(50)



  coordinate1 = ninja.xcor()

  new1 = coordinate1+50

  ninja.penup()
  ninja.goto(new1,0)



h()
i()
name = input('What is your name. It will be drawn in the tab to the left lowercase only please.')
print('The name will begin to draw in the tab to the left')
sleep(3)
ninja.clear()
ninja.goto(0,0)

name =  list(name)
print(name)
length = len(name)
x=0
while (x < length-1):         
  print(name[x])
  x = x + 1

  new2=name[x]+'()'
  eval(new2)
  print(new2)

1 个答案:

答案 0 :(得分:0)

您可以使用字典:

letter_movements = {'h': h, 'i': i}

然后,当您想运行该函数(在其中有eval的位置)时,只需从字典中进行选择:

letter_movements[new2]()