yes/no loop not working properly when i used OR keyword

Question:

I was using a yes/no loop to make an infinite loop which would end when user enters no or No but the program was not working properly. I know the what the error is but i don’t know why is it occuring like this. Can anyone tell how to fix the error without changing my initial program

when i use this code it works but when i use if a==’yes’ or ‘Yes’ and elif a==’no’ or ‘No’ in the somehow the output shows the print statement of the if statement even when i enter no.

My program without the OR condition

while True:
    a = input("Enter yes/no to continue")
    if a=='yes':
        print("enter the program")
    elif a=='no':
        print("EXIT")
        break
    else:
        print("Enter either yes/no")

My initial program with OR condition

while True:
    a = input("Enter yes/no to continue")
    if a=='yes' or 'Yes':
        print("enter the program")
    elif a=='no' or 'No':
        print("EXIT")
        break
    else:
        print("Enter either yes/no")
Asked By: Abhijeet

||

Answers:

You have a few options:

while True:
    a = input("Enter yes/no to continue")
    if a.lower()=='yes':
        print("enter the program")
    elif a.lower()=='no':
        print("EXIT")
        break
    else:
        print("Enter either yes/no")

or you can do this:

while True:
    a = input("Enter yes/no to continue")
    if a=='yes' or a=='Yes':
        print("enter the program")
    elif a=='no' or a=='No':
        print("EXIT")
        break
    else:
        print("Enter either yes/no")
Answered By: ScottC

In an or statement you have to compare a with the value in all expressions:

while True:
    a = input("Enter yes/no to continue")
    if a == 'yes' or a == 'Yes':
        print("enter the program")
    elif a == 'no' or a == 'No':
        print("EXIT")
        break
    else:
        print("Enter either yes/no")

A more pythonic way is to use .lower() in your case. For example:

a == 'yes' or a == 'Yes'  # is equeal to:
a.lower() == 'yes'
Answered By: smnenko

When you use or, you should write complete condition again.

Here if you want to check a=="Yes" also, you should declare it completely.

if a == 'yes' or a == 'Yes':
...

You can also use this:

if a.lower() == 'yes'
...
Answered By: Amin
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.