I'm working on some homework and have been tasked with creating a simple program that:
- Gets user input
- Check that said input is in the correct form (two words with ',' separating)
- Outputs the input as two separate words
- And loops all of the above until 'q' is input
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.
1 Answer 1
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)
8 Comments
while condition: thing(). For this example it would be while usrStr != 'q': #etc.. and removing the break. Infinite loops are not always needed, but I tend to use them a lot as well.while loop conditions are evaluated only after every iteration, meaning that the code within the while loop will still be executed once before the loop condition evaluates and breaks out of the loop. i.e. pastebin.com/4DsPSnKd