I am doing an exercise where the user can enter an expression, to perform a sum. However, I see that it fails in a certain part of the program. Instead of changing the variable x (in this example x*2) what it does is add 2 times 2 + 2 times 2..., instead of 2 times 2 + 3 times 2 + 4 times 2, so the variable x is not increasing (or in this case it is the variable count or min_num). Here is the code:
variable = "x"
min_num = 2
max_num = 5
result = 0
sum = 0
def summation(expression):
global min_num, max_num
count = min_num
while count <= max_num:
expression = expression.replace(variable, str(min_num))
print(expression)
global result
result = eval(''.join(expression))
global sum
sum += result
count += 1
min_num += 1
return sum
print(summation("x*2"))
This is the output:
2*2
2*2
2*2
2*2
16
And the desired one is this:
2*2
3*2
4*2
5*2
28
The error is here:
In this you replace
expression
, originally"x*2"
with its replacement,"2*2"
.The second time you go through there, there is no "x" to replace.
Solution: Use an intermediate variable
show
Note: There's no point in declaring local variables if you're only going to use them inside a function, which is why I've moved them to their proper location. print(summation("x*2"))
produces: