0
import sys
total = 0

while True:
    try:
        num = float(input("Enter a number: "))
        print(num, "has been added to the total")
        total += num
    except:
        print("This is not a number. Please re-enter")
        continue
    while True:
        again = input("Would you like to enter another number to add (Y or N)? ")
        if again == "Y" or "y":
            break     
        elif again == "N" or "n":
            print("The sum of the numbers is:", total)
            sys.exit()
        else:
            print("Invalid response. Please enter Y or N")

My issue is after I introduced the second while loop. It seems only to be processing the if again == "Y" or "y": It will break and go back to the first loop which is what I want. However it does not process the rest of the conditions. Like if the input is "N" or anything else, it will break and ignore what I have it set to do. Your help is very appreciated.

Cherry
  • 191
  • 1
  • 3
  • 9

1 Answers1

2

You are having trouble with this expression:

        if again == "Y" or "y":

Order of operator precedence says it is equivalent to this expression:

        if (again == "Y") or ("y"):

The value of the 1st term doesn't much matter, since the 2nd term is not None, so it evaluates True, so the whole boolean expression will always evaluate True.

What you wanted was something along the lines of:

        if again in {'Y', 'y'}:

which is testing set membership. Remember to adjust the 'N' expression, as well.

Or, for the higher-level problem, you might choose a different tack:

        if again.lower() == 'y':
J_H
  • 17,926
  • 4
  • 24
  • 44