0

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")
Abhijeet
  • 3
  • 3
  • 1
    Try ```a.lower() == 'yes'``` and ```a.lower() == 'no'``` – Maxwell D. Dorliea Nov 26 '22 at 09:24
  • because `a=='yes' or 'Yes'` is equivalent to `(a=='yes') or 'Yes'` Since `'Yes'` is always truthy, the statement is *always true*, regardless of whether or not `a == 'yes'`. You want `a == 'yes' or a == 'Yes'`, or in this case, as other have suggested, `a.lower() == 'yes'` or the equivalent – juanpa.arrivillaga Nov 26 '22 at 09:37

3 Answers3

0

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")
ScottC
  • 3,941
  • 1
  • 6
  • 20
0

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'
cafce25
  • 15,907
  • 4
  • 25
  • 31
smnenko
  • 101
  • 4
0

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'
...
Amin
  • 2,605
  • 2
  • 7
  • 15