I'm programming a calculator.
For example, I have the following:
result = 0
splitted_calculation = ["2", " ", "2"]
for thing in splited_calculation:
if thing == " ":
result = result number
else:
number = int(thing)
print(result)
I want that, if the variable in the for loop is an integer, then that value is stored such that I can add the previous integer to the next integer currently in the for loop. However, when I run the code, I always get 0. It seems that the "number = int(thing)" isn't working. Any tips to solve this?
CodePudding user response:
The issue with your code (besides the typo) is that the last digit is ignored. Step through it - in your head, on paper, or with a debugger.
Iterations of the loop. For this example, change it to ['2',' ','3']
for clarity:
SIteration | thing |
Action | number |
result |
---|---|---|---|---|
1 | 2 | assign it to number |
2 | 0 |
2 | add number to result |
2 | 2 | |
3 | 3 | assign it to number |
3 | 2 |
After the loop, the last digit is just hanging out in number
but was never added to result
. So result
ends up at 2
not 5
.
If the format is always "number operator number" there is no need for a loop. Access the values directly from the list:
splitted_calculation = ["2", " ", "2"]
left_number = int(splitted_calculation[0])
right_number = int(splitted_calculation[2])
operator = splitted_calculation[1]
if operator == ' ':
result = left_number right_number
elif operator == '-'
result = left_number - right_number
# repeat for others.
If the formulas are more complex ("2 2 2" for example) you can modify the loop to store the last operator and do the math on the numbers:
splitted_calculation = ["-5", " ", "2", "-", "3"]
result = 0
last_op = " "
for n in splitted_calculation:
if n in " -*/":
last_op = n
else:
if last_op == ' ': result = int(n)
elif last_op == '-': result -= int(n)
elif last_op == '*': result *= int(n)
elif last_op == '/': result /= int(n)
Output:
-6
CodePudding user response:
Find Modified Code Below:
result = 0
splited_calculation = ["2", " ", "2"]
for thing in splited_calculation:
if thing != " ":
result = int(thing)
print(result)