1

I don't know what is the problem, but I can't end a while loop if it is under two if conditions. Let me show the code:

while True:
    k = input ("Please enter 'hello': ")
    if k == "hello":
        m = input ("Are your Sure? (Y/N): ")
        if m == "Y" or "y" or "yes" or "Yes":
            break

Now, after the second prompt, even if i type no or any other things, while loop still ends. I only want to end it after second confirmation. What is my mistake in the coding?

Sheikh Ahmad Shah
  • 281
  • 1
  • 4
  • 12

3 Answers3

5

This is what internally happens.

Your code:

m == "Y" or "y" or "yes" or "Yes"

Python Interpretation:

(m == "Y" )or ("y" or "yes") or "Yes"

("y" or "yes") will always produce y since it is not a falsey value then ("y" or "yes") or "Yes" is changed to this "y" or "Yes" again same value so finally (m == "Y" )or ("y" or "yes") or "Yes" is changed to (m == "Y" )or "y"

To avoid this you could use separate checking for all the condition or in as BenC stated

Or Even more simply

m.lower() in "yes" # Note that it also True if m is e or es or s etc..

      or

"yes".startwith(m.lower()) # This work perfectly as per my test cases
The6thSense
  • 8,103
  • 8
  • 31
  • 65
1

It should look like this:

if m == "Y" or m == "y" or m == "yes" or m == "Yes":

scope
  • 1,967
  • 14
  • 15
1

change or condition

Demo:

>>> while True:
...     k = raw_input ("Please enter 'hello': ")
...     if k == "hello":
...         m = raw_input ("Are your Sure? (Y/N): ")
...         if m == "Y" or m == "y" or m == "yes" or m == "Yes":
...             break
... 
Please enter 'hello': hello
Are your Sure? (Y/N): y
>>> 

we can use lower string method to convert string to lower case,

Demo:

>>> m = raw_input ("Are your Sure? (Y/N): ").lower()
Are your Sure? (Y/N): Yes
>>> m
'yes'

Note:

Use raw_input() for Python 2.x

USe input() for Python 3.x

Vivek Sable
  • 9,938
  • 3
  • 40
  • 56