wd********@gmail.com a écrit :
Hmm, my while loop with "or" doesn't seem to work as I want it to...
How do I tell the while loop to only accept "Y" or "y" or "N" or "n"
input from the str(raw_input)?
Thank's in advance!
Snippet of code:
import os
def buildfinder():
os.system("CLS")
GameRoot = os.getenv("GAME_ROOT") + "\\"
print "Do you want to use " + GameRoot + " as your source
directory?"
usr = str(raw_input('Y/N: '))
return usr
#Runs the buildfinder function
usrinp = buildfinder()
def buildwhiler():
while usrinp != "y" or "Y" or "N" or "n": <<<<----PROBLEM
Yes, obviously.
The above reads as:
while (usrinp != "y") or ("Y") or ("N") or ("n"):
What you want is something like:
while usrinp != "y" and usrinp != "Y" \
and usrinp != "n" and usrinp != "N" :
which is better written as
while not (usrinp == "y" or usrinp == "Y" \
or usrinp == "n" or usrinp == "N") :
which can be simplified using str.lower:
while not (usrinp.lower() == "y" or usrinp.lower() == "n"):
and simplified again thanks to Python 'in' operator:
while not usrinp.lower() in "yn":
print "Enter Y or N!"
usr = str(raw_input('Y/N: '))
else:
code continues
While we're at it, there are other problems in your code. One of them is
that buildwhiler() will go in an infinite loop if the usr first typed
anything else than "y", "Y", "n" or "N". I let you try to find out why,
and just give you two hints :
- globals are Bad(tm)
- don't mix application logic with user-interface logic (ie: a function
should only deal with one or the other, not mix both).
HTH