Search code examples
python-2.7raw-input

How To Make raw_input Not A String In python


I want to make this program do the summation of something with their input. My code thus far

def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
eqn = lambda n: raw_input("Equation?: ")
sum = 0

for i in range(start , end + 1):
    sum += eqn(i)

return sum
print summation() # start will be 1, end will be 5 , equation will be n + 1. Should print 20

I get the error that I can't add an integer and a string together so is there any way to make the raw_input for equation not a string. Like instead of it being 'n + 1', I want it to be n + 1.


Solution

  • You could use input instead of raw_input, but this isn't really a good idea, since every time eqn is called it will call a input and prompt you for the equation.

    A better method is to store the equation beforehand (using raw_input), and then use eval in the lambda function. Something like:

    def summation():
        start = int(raw_input("Start value of n?: "))
        end = int(raw_input("End value of n?: "))
        fx  = raw_input("Equation: ")
        eqn = lambda n: eval(fx)
        sum = 0
    
        for i in range(start , end + 1):
            sum += eqn(i)
    
        return sum
    
    print summation()