Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Assignment with or
#1
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?
Reply
#2
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).
Mark17 likes this post
Reply
#3
Thanks bowlofred!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020