If-elif-else statement not working in simple Python 3.3 class?

Question:

My code is:

def nameAndConfirm():
    global name,confirm
    print("What is your name? ")
    name = input()
    str(name)
    print("Is",name,"correct? ")
    confirm = input()
    str(confirm) 
    print(confirm)

    if confirm.upper() == "Y" or "YES":
        classSelection()
    elif confirm.upper() == "N" or "NO":
        nameAndConfirm()
    else:
        print("Valid answers are Y/Yes or N/No!")
        nameAndConfirm()

nameAndConfirm()

Critique on this code would be nice as well. I know its very shifty, I know how to make it shorter in some ways but I was trying to get my if-elif-else to work. I have no clue what else I can do as I’ve tried everything I know. Also I made an indent 4 spaces in the above code. **Edit: sorry the error is that it always runs the “if” it never goes past the first if line no matter what you enter in for confirm

Asked By: user1486297

||

Answers:

The condition confirm.upper() == "Y" or "YES" and the other one are not evaluated as you expect. You want

confirm.upper() in {"Y", "YES"}

or

confirm.upper() == "Y" or confirm.upper() == "YES"

Your condition is equivalent to:

(confirm.upper() == "Y") or "YES"

which is always truthy:

In [1]: True or "Yes"
Out[1]: True

In [2]: False or "Yes"
Out[2]: 'Yes'

On a separate note, the lines

str(name)

and

str(confirm)

don’t do anything. The values returned by the functions are not saved anywhere, and name and confirm are not altered. Moreover, they are already strings to begin with, because they hold the return values of input().

Answered By: Lev Levitsky

That’t not the correct way to implement "or" in your if condition:

confirm.upper() == "Y" or confirm.upper() == "YES"

It should be like this

Answered By: Ashok
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.