Hi there, I'm a real newbie to python so sorry if this is a stupid question or if I don't fully get your answer, no hate please!

I'm trying to write a small program to use when calculating differential equations bu using Euler's step method, don't worry if you don't know what that is, it's not important. My code looks like this:

#!/usr/bin/python3.3 -tt
import sys
def main():
    x = float(input("Ange x - värde: "))
    y = float(input("Ange y - värde: "))
    print ("(",x,",",y,")")
    h = float(input("Ange steglängd: "))
    limit = float(input("Till vilket x - värde önskas gå: "))
    while x < limit:
        a  = (2 * x) + y
        y = (a * h) + y
        x = x + h
    print ("(",x,",",y,")") 
main()

This works FINE, but what I'd really like to be able to to is for the user to be able to enter (via input) a function for the variable a, instead of me having to define it in the very code of the program. Is there a way of doing this?

Thanks for any help! (BTW the language in the code is Swedish)

It can be done with the eval() builtin function. However!!! it is very dangerous to allow users to input any old thing and then evaluate that input. It would be better to give them a limited set of choices.

Thank you very much! This helped me a lot! Since I'm not that good at python, I still have some problem with getting it to work. Maybe you know how to fix?

I wrote a small test program to see if I could get it to work, and it looks like

    x = (input("Ange x - värde: "))
    y = float(input("Ange y - värde: "))
    print ("(",x,",",y,")")
    deriv = input("Y' = ")
    deriv = float(deriv)
    print (eval(deriv))

but the problem is that, when I in the program enter that x=1 and deriv should be equal to 2*x it prints 11, since it take it as a command to print the value of x two times. How can I make i actually do the calculation and print in this case 2 instead of 11?

Again, Thanks A lot!

I suggest to read expressions and use lambda to create a python function

deriv = input("Y' = ") # enter for example 2 * x
func = eval("lambda x: " + deriv.strip())
# now func(3.7) --> 7.4

Also, you cast Y to float() but not X so it remains a string: 2*"1"="11"
[never mind: I see you're in v3.3 so input should take care of the conversion properly. AS Gribouillis said...]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.