0

This loop keeps looping even if I enter "no" and when I type "jdlfjap", for example, it continues to loop without a "?".

Does anyone know why this is?

def makeContact():
    contactName = input("Name: ")
    contactNumber = input("Number: ")
    dictionaryForContacts[contactName] = contactNumber
def continueMaking():
    while True:
        continueMaking = input("\nWould you like to continue making contacts? ")
        if continueMaking == "Yes" or "yes" or "YES":
            makeContact()
            continue
        elif continueMaking == "No" or "no" or "NO":
            break
        else:    
            print ("?")
            continue
Daniel
  • 161
  • 2
  • 9
  • `continueMaking == "No" or "no" or "NO"` doesn't do what you think it does. It doesn't compare `continueMaking` to each of those 3 words. – lurker Nov 07 '15 at 22:36
  • Use `lower()` or checkout [`in`](https://docs.python.org/3/reference/expressions.html#in) – sam Nov 07 '15 at 22:37
  • Rewrite as `if continueMaking in ("Yes", "yes", "YES")` or `if continueMaking.strip().lower() == "yes"` – dawg Nov 07 '15 at 22:42
  • Possible duplicate of [Compare multiple variables to the same value in "if" in Python?](http://stackoverflow.com/questions/8641008/compare-multiple-variables-to-the-same-value-in-if-in-python) – Peter Wood Nov 07 '15 at 22:45
  • You can try things in the interactive prompt: `>>> "no" == "Yes" or "yes" or "YES"` gives `'yes'` – Peter Wood Nov 07 '15 at 22:47

2 Answers2

2

The statement if continueMaking == "Yes" or "yes" or "YES": is equivalent to (continueMaking == "Yes") or "yes" or "YES": which, regardless of the value of continueMaking returns the string "YES", which is truthy and thus the makeContact call always executes. Case-insensitive string comparisons can be accomplished by continueMaking.lower() == "yes".

pppery
  • 3,731
  • 22
  • 33
  • 46
  • 1
    Great answer, but probably should be `continueMaking.strip().lower() == "yes"` to catch trailing spaces. – dawg Nov 07 '15 at 22:44
  • Based on [operator precedence](https://docs.python.org/2/reference/expressions.html), why wouldn't it be evaluated to `continueMaking == true` since `or` has a higher precedence and it would be coerced into a boolean? – BLaZuRE Nov 07 '15 at 22:45
  • Nope, that statement simplifies to `True if continueMaking == "Yes" else "yes"`. – pppery Nov 07 '15 at 22:50
1

Overwriting the function continueMaking with the variable continueMaking adds confusion. Choose a different variable name. Readability counts.

jwvh
  • 50,871
  • 7
  • 38
  • 64
garyboland
  • 135
  • 12