Python Forum

Full Version: Assignment with or
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

Here's my code

def arithmetic_arranger(problems,answers=False):
  for problem in problems:
    print(problem)
    if '+' not in problem and '-' not in problem:
      print("Error:  Operator must be '+' or '-'.")
      quit()
    temp = problem.replace(' ','')
    print('temp is',temp)
    loc = temp.find('+') or temp.find('-') #index of operator
    if loc > 3:
      print("Error:  Numbers cannot be more than four digits.")
      print('first one')
      quit()
    elif len(temp) - loc > 4:
      print('len(temp) is',len(temp))
      print('loc is',loc)
      print("Error:  Numbers cannot be more than four digits.")
      quit()
    for char in problem:
      if char not in ['+','-',' ']:
        if char.isdigit()==False:
          print('Numbers must only contain digits.')
          quit()
  if len(problems)>5:
    print('Error: Too many problems.')
    quit()

  return type(problems)
Second time through, after printing '3801-2', it prints 'loc is -1.' Why does line 9 not identify this as 4?
or will return the first argument unless it is a false value. If that happens, then it will return the second argument.

The first argument here is temp.find('+'). But since a character can appear in position 0, if the character isn't present at all, it will return -1. But -1 is not a false value.

>>> 0 or 5
5
>>> -1 or 5
-1
So rather than checking for truth, you might want to check if it does not equal -1 (or if it's greater than -1).
Thanks bowlofred!