-2

Simply put, what my code is supposed to do is to add user-inputted sums to u for later use. The sums are in the form 'number operator number' Anyways, I want to make it such that only + and - are accepted as operators, not * and /. Yet, I seem to be able to key in equations with the latter operations. Furthermore, the numbers added can only be up to a maximum of 4 digits. However, when I key in even single-digit numbers, the except code still trips. Please tell me where I went wrong. Thank you.

while True: sum = input("Pls enter a math problem: ")

count = count + 1
if sum.lower() == 'done':
    break
elif count > 5:
    print('Error: Too many problems')
    break
else:
    try:
        digits = sum.split(' ')
        operand_1 = digits[0]
        operator = digits[1]
        operand_2 = digits[2]
        print(operator)

    except:
        print('Put a space in between each number and operator')
        sum_list = [ ]

    try:
        operand_1 = int
        operand_2 = int
    except:
        print('Error: Numbers must only contain digits.')
        sum_list = []

    **try:
        operator == "+" or "-"
    except:
        print('Error: Operator must be "+" or "-".')
        sum_list = []**
    try:
        len(operand_1) < 4
        len(operand_2) < 4
    except:
        print('Error: Numbers must only contain maximum of 4 digits.')
        sum_list = [ ]
sum_list.append(sum)

print(sum_list)

  • `operand_1 = int` will never raise an exception. `operator == "+" or "-"` will never raise an exception either. And neither will `len(operand_1) < 4`. – deceze Nov 26 '21 at 12:48

1 Answers1

1
  1. That's not how or works with ==. Could be rewritten as if operator == "+" or operator == "-" or if operator in ["+", "-"]
  2. except intercepts exceptions. That == expression will never raise an exception. Did you mean to use an if/else instead of try/except here?
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367