0

I made this calculator in python that should add whatever value i give it and store the results in a variable. Then if my input in something other than the numbers, it should print the results....It does not give any error, but it prints the results as 0. Why are the numbers not being added even though i clearly added them.

while True:
    inpt = input("> ")
    calc = 0
    if inpt == "1":
        calc += 1
    elif inpt == "2":
        calc += 2
    elif inpt == "3":
        calc += 3
    elif inpt == "4":
        calc += 4
    elif inpt == "5":
        calc += 5
    elif inpt == "6":
        calc += 6
    elif inpt == "7":
        calc += 7
    elif inpt == "8":
        calc += 8
    elif inpt == "9":
        calc += 9
    else:
        break

print(calc)
1
  • 2
    Because on every iteration of your infinite while loop, you set calc=0. Just put the calc=0 statement outside of the loop. Commented May 2, 2020 at 10:39

1 Answer 1

2

At each run, you reassign 0 to calc, so you reset the previous run, put it outside

calc = 0
while True:
    inpt = input("> ")
    # ...

Also you may just convert the string as int to avoid such if/else, if it's a digit

calc = 0
while True:
    inpt = input("> ")
    if inpt not in "123456789":
        break
    calc += int(inpt)
1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.