Is there a way to create a loop which while only stop if specific strings are entered?
What I'm trying to do is make a loop which prompts the user for information and will only stop if certain strings are entered. Specifically, I want it only to accept certain letters, both upper and lowercase. Here's what I have so far:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP != "C" || salesP != "c")
Basically the while part is completely wrong and I know it. I've tried everything I can think of, and the best I can do is get it to accep开发者_如何学Pythont a single variable. I also need it to accept d, x, and m, both cases.
Option 1 Permanent loop with an if statement, can use multiple if statements or other control structures to check for when to break.
while 1:
if(raw_input('Enter some data please:') == specialString):
break
Option 2 Part of loop
tempstring = ""
while (tempstring != specialString):
tempstring = raw_input('Enter some data please:')
Option 3: Recursion
def dataEntry(a,b,c):
#data validation statements that fail on first iteration
#statements to prompt user about data
dataentry(a,b,c)
As far as how to check for the right string, I would recommend regular expressions. Googling for "regex" examples is much better than me trying to explain it.
Something else to play with that if you are new you should become REALLY familiar with when doing string comparison is to eliminate case from the equation completely:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP.toLowerCase() != 'c')
That code is almost correct. You simply use the incorrect boolean operator in your while statement. You're using OR (||
) where you should use AND (&&
).
So:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP != "C" && salesP != "c")
just another approach
function promptSalesP(){
var _salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
if(_salesP.toLowerCase() == "c")
return _salesP;
else
return promptSalesP();
}
var salesP = promptSalesP();
精彩评论