Reputation: 49
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
Upvotes: 0
Views: 402
Reputation: 39023
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]()
Upvotes: 1
Reputation: 798774
def docircle(pen):
pen.forward(100)
pen.left(91)
commands = {
'circle': docircle,
...
}
...
commands[turtleCommand](t)
Upvotes: 1
Reputation: 298246
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)
Upvotes: 1