Error with raw_input

1

I need to calculate the Laplace transform. For that I used the following code:

from sympy.abc import x, s
from sympy import Symbol, exp, cos , sin , Heaviside, integrate, limit, oo

x=Symbol("x")
s=Symbol ("s")
f=raw_input(" write any function : ")
integral= integrate( exp(-s*x) * cos(3*x) ,(x,0,oo), conds="none")
print integral

The problem is that having f with raw_input , when the user enters the code f takes value of string so I throw error.

This is an example if f takes the value of

f=3*x

he tells me:

integral= integrate( exp(-s*x) * f ,(x,0,oo), conds="none")
TypeError: can't multiply sequence by non-int of type 'exp'

Any ideas on how to fix this?

    
asked by Daniel Vildosola 05.06.2017 в 10:07
source

2 answers

2

Indeed, it is because raw_input returns a string and an expression is expected. The solution is to parse the string to a valid sympy expression. For that we can help us from sympy.parsing.sympy_parser :

from sympy.abc import x, s
from sympy import Symbol, exp, cos , sin , Heaviside, integrate, limit, oo
from sympy.parsing.sympy_parser import parse_expr

x=Symbol("x")
s=Symbol ("s")
f= parse_expr(raw_input(" write any function : "))
integral= integrate( exp(-s*x) * f ,(x,0,oo), conds="none")
print integral

Sample exits:

  

write any function: x * 3
  3 / s ** 2

     

write any function: cos (3 * x)
  s / (9 * (s ** 2/9 + 1))

You can use input instead of raw_input but this should be avoided whenever possible : input evaluates any valid Python expression, so that we enable the user to enter any Python code and do what he wants with the system. Using input (or eval in Python 3) is exposing yourself to code injection attacks unnecessarily and it is a bad practice if it can be avoided.

As a dumb example, nothing prevents the user from entering something like os.system('rm -rf /') and loading the system files if we have the bad luck of having imported os in our module ....

    
answered by 05.06.2017 в 16:57
1

You can put a function that transforms the value to integer

def convertStr(s):
try:
    ret = int(s)
         except ValueError:
    #Try float.
         ret = float(s)
return ret

Casting the Raw Input directly to an int

int(raw_input(""))

Although I would use the Input function, since with it you can evaluate what the user enters as an input parameter

link

    
answered by 05.06.2017 в 15:39