[英]How To create a shortcut for a command in python 3.3
I just started learning python and was wondering if their was a way to shortcut a line of code. 我刚刚开始学习python,想知道它们是否是一种捷径代码行的方法。 For example could I use something along the lines of. 例如,我可以使用类似的东西吗?
command = input()
if command = "create turtle"
t =turtle.Pen()
or 要么
turtleCommand = input()
if turtleCommand = "circle"
t.forward(100)
t.left(91)
The turtle thing is just hypothetical maybe if a string "inputted" (if thats a word) activated a defineFunction 乌龟的事情只是假设的,如果一个字符串“输入”(如果是一个单词)激活了defineFunction
You can write a function: 您可以编写一个函数:
def draw_circle(t):
t.forward(100)
t.left(91)
And then call it: 然后调用它:
t = turtle.Pen()
command = input()
if command == "circle":
draw_circle(t)
elif command = "stuff":
...
A more robust solution would be to use a dictionary that maps commands to functions: 一个更可靠的解决方案是使用将命令映射到功能的字典:
commands = {
"circle": draw_circle,
"square": draw_square
}
And then get a function by name: 然后按名称获取一个函数:
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)
You can set up a dictionary mapping a word to the function you want the word to activate: 您可以设置字典,将单词映射到您希望单词激活的功能:
commands = {'create turtle': create_turtle,
'circle': circle, }
def create_turtle():
t = turtle.Pen()
def draw_circle():
...
And then: 接着:
command = input()
commands[command]()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.