I'm writing a simple python script to solve differential equations using Eulers method and right now i have to change the source code every time i want to solve a new equation.
(Safety isn't of any concern at the moment as this is a personal project.)
My question:
Would it be possible to type in an equation as user input and make it to a variable? For example, using e=input("enter equation")
where you enter y/x
, and making e
a variable for later use?
#I would like to be able to type in a equation as user input and turn it to a variable for later use in the if and elif segments, example
e=input("Enter your equation here")
e=float(e)
h=input("Ange steglängd: ")
h=float(h)
x=input("Angivet värde på x: ")
x=float(x)
y=input("Värde på y med anseende på x: ")
y=float(y)
z=input("Närmevärde du vill ha för y(x), ange x: ")
z=float(z)
if x<z:
while x<z:
#Type in equation below as e
e=y/x
y=y+h*e
x+=h
print(y)
elif x>z:
while x>z:
e=y/x
y=y-h*e
x-=h
print(y)
Tack för exempel -- that allowed me to determine what you need.
Yes, this is possible. Read in the equation as a string variable, such as
equation = input("Enter your equation here")
Then when you want to find a value for e, use the Python eval method:
e = eval(equation)
Be very careful with this method: eval()
is powerful, and very discriminating about what it accepts.