我是编程和目前在学校的新手。我有一个分配问题,我需要为多个输入创建一个循环,直到用户输入q结束。现在这个问题作为一个整体的分配已经在链接到Trying to hammer out this zylabs Lab but struggling之前被询问了,我一直在关注@Splatmistro列表以完成大部分的任务。但是,我只需要帮助就能理解我的代码中缺少什么才能正常工作。
input_comma = input('Enter input string: \n')
**if input_comma != 'q':**
while ',' not in input_comma:
print('Error: No comma in string.')
input_comma = input()
print('Enter input string: ')
split_input = input_comma.split(',')
print('First word:',split_input[0].strip())
print('Second word:',split_input[1].strip())
我知道我需要在while语句之前使用IF语句,但我所拥有的语句似乎并不起作用。我知道我错过了一些东西,但我无法弄清楚。非常感谢任何帮助。
EDITED:这是我正在处理的代码的预期输出。
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
我的代码将正确拍摄并打印第一个输入,但不会继续循环输入第二个,第三个或第四个输入。这就是我要求帮助的地方。
答案 0 :(得分:1)
使用另一个if
循环,而不是使用while
语句,如下所示:
input_comma = input('Enter input string: \n')
while input_comma != "q":
while "," not in input_comma:
print('Error: No comma in string.')
input_comma = input()
print('Enter input string: ')
split_input = input_comma.split(',')
print('First word:',split_input[0].strip())
print('Second word:',split_input[1].strip())
input_comma = input('Enter input string: \n')
请注意,我还缩进了最后三行...这使得程序根据您提供的示例帖子工作。