Python User input equation

后端 未结 2 1599
轻奢々
轻奢々 2020-12-21 08:06

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 equat

相关标签:
2条回答
  • 2020-12-21 08:24

    You can use the eval in combination with lambda functions, like this:

    e = eval('lambda x, y: x/y')
    

    To actually have this interactive, use raw_input() to obtain the actual expression ('lambda x, y: x/y' in this case). Or if you prefer not to type the whole lambda wording, and provided that you'll always have the independent variable x and the dependent variable y, in an equation like y = f(x), you could write something like this:

    e = eval('lambda x, y: ' + raw_input('enter equation for y=f(x): '))
    

    And then you'd enter the 'x/y' when you're prompted to.

    However, are you sure you need it inside the while loop?

    0 讨论(0)
  • 2020-12-21 08:48

    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.

    • eval is really dangerous
    • Security on untrusted strings
    0 讨论(0)
提交回复
热议问题