简体   繁体   中英

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. 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

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]()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM