[英]How To create a shortcut for a command in python 3.3
我刚刚开始学习python,想知道它们是否是一种捷径代码行的方法。 例如,我可以使用类似的东西吗?
command = input()
if command = "create turtle"
t =turtle.Pen()
要么
turtleCommand = input()
if turtleCommand = "circle"
t.forward(100)
t.left(91)
乌龟的事情只是假设的,如果一个字符串“输入”(如果是一个单词)激活了defineFunction
您可以编写一个函数:
def draw_circle(t):
t.forward(100)
t.left(91)
然后调用它:
t = turtle.Pen()
command = input()
if command == "circle":
draw_circle(t)
elif command = "stuff":
...
一个更可靠的解决方案是使用将命令映射到功能的字典:
commands = {
"circle": draw_circle,
"square": draw_square
}
然后按名称获取一个函数:
t = turtle.Pen()
turtle_command = input()
command = commands[turtle_command]
command(t)
def docircle(pen):
pen.forward(100)
pen.left(91)
commands = {
'circle': docircle,
...
}
...
commands[turtleCommand](t)
您可以设置字典,将单词映射到您希望单词激活的功能:
commands = {'create turtle': create_turtle,
'circle': circle, }
def create_turtle():
t = turtle.Pen()
def draw_circle():
...
接着:
command = input()
commands[command]()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.