1

I want to make simple program that asks user what function (mathematical) he wants to see and then program draws it with turtle. I have drawing done but user input is tricky, I am sure you can't do that in one line of code but how to convert the input (string) into something like x * 10 + 30 - x, that can be put in function call

Ex.: function(x, x * 10 + 30 - x)

My code:


print("Give function you want to see, don't do '2x', do 'x * 2', after and before signs like '+ * /' do space, USE ONLY X AND NUMBERS")
print("Example: x * x + 10 - x * 2")
print("Give function you want: ")

functionS = input()


def drawNewThing(x, function):
    goto(x * 2, function)

for i in range(100):
    drawNewThing(i, functionS)
Peter O.
  • 32,158
  • 14
  • 82
  • 96

1 Answers1

0

You can use eval to evaluate the expression, but make sure the x variable must be defined before evaluating the expression.

The eval will directly execute expression by keeping value of x in the expression.

try below code

def drawNewThing(x, function):
    function = eval(function)
    goto(x * 2, function)
Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19
  • This is assuming the user input is both valid AND safe. Using eval could be exploited by someone passing malicious code into input() – IAmBullsaw Apr 19 '21 at 07:53