Reputation: 59
I'm working on some homework and have been tasked with creating a simple program that:
It has to come out exactly like asked, and I have it doing so at the moment. I just can't figure out how to loop the prompt back and get different input without it being an infinite loop or never actually taking the new input.
Here is what the output should look like once done:
Enter input string:
Jill, Allen
First word: Jill
Second word: Allen
Enter input string:
Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string:
Washington,DC
First word: Washington
Second word: DC
Enter input string:
q
I can get it through the first entry and make it quit with 'q,' but can't get it to prompt the user again and get a different input.
Here is my code:
def strSplit(usrStr):
while "," not in usrStr:
print("Error: No comma in string.\n")
usrStr = input("Enter input string:\n")
else:
strLst = usrStr.split(",")
print("First word: %s" % strLst[0].strip())
print("Second word: %s\n" % strLst[1].strip())
usrStr = input("Enter input string:\n")
while usrStr != 'q':
strSplit(usrStr)
break
Any help would be fantastic! Thank you.
Upvotes: 0
Views: 92
Reputation: 16593
You're almost there. Try this:
while True:
usrStr = input("Enter input string:\n")
if usrStr == 'q':
break
if "," not in usrStr:
print("Error: No comma in string.\n")
else:
strLst = usrStr.split(",")
print("First word: %s" % strLst[0].strip())
print("Second word: %s\n" % strLst[1].strip())
Of course, you could still use your strSplit
function with some modifications:
def strSplit(usrStr):
if "," not in usrStr:
print("Error: No comma in string.\n")
else:
strLst = usrStr.split(",")
print("First word: %s" % strLst[0].strip())
print("Second word: %s\n" % strLst[1].strip())
while True:
usrStr = input("Enter input string:\n")
if usrStr == 'q':
break
strSplit(usrStr)
Upvotes: 2