How can I fill in turtle directions in a list using Python? -


i have list of turtle directions:

redlist = ['seth(0)', 'forward(drawdist)', 'seth(0)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)'] 

how can fill in using list?

although list of syntactically correct python statements seems opportunity use eval(), resist temptation. syntax here simple enough, function 1 argument, can use re module parse commands , execute appear valid functions against valid arguments:

import turtle import re  redist = [ \     'seth(0)', 'forward(drawdist)', 'seth(0)', 'forward(drawdist)', \     'seth(90)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', \     'seth(180)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', \     'seth(270)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)' \     ]  valid_functions = { \     'seth': turtle.setheading, \     'forward': turtle.forward, \     }  valid_arguments = { \     'drawdist': 50, \     }  turtle.begin_fill()  command in redist:     match = re.match(r"^(\w+)\((\w+)\)$", command)      if match none:         raise syntaxerror("invalid syntax")      function, argument = match.group(1), match.group(2)      if function not in valid_functions:         raise valueerror("invalid function")      if argument in valid_arguments:         argument = valid_arguments[argument]     elif argument.isdigit():         argument = int(argument)     else:         raise typeerror("invalid argument")      valid_functions[function](argument)  turtle.end_fill()  turtle.hideturtle()  turtle.mainloop() 

for want read ahead, draws filled square. exceptions raise above may not correct ones point need error check everything, , raise exceptions, when attempting execute code that's been handed string.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -