程序重复,直到输入字符串退出并忽略后面的整数输入

The program repeats until the input string is quit and disregards the integer input that follows

编写一个程序,将一个字符串和一个整数作为输入,并使用输入值输出一个句子,如下例所示。程序重复,直到输入字符串退出并忽略后面的整数输入。

例如:如果输入是:

apples 5
shoes 2
quit 0

输出为:

Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.

这是我目前得到的:

string = input().split()
string2 = input().split()
string3 = input().split()

all_input = (string + string2 + string3)

for word in all_input:
    while word != 'quit':
        print('Eating {} {} a day keeps the doctor away.'.format(string[1] , string[0]))
        print('Eating {} {} a day keeps the doctor away.'.format(string2[1], string2[0]))
        string = input().split()
        string2 = input().split()
        string3 = input().split()
        all_input = (string + string2 + string3)

我得到了正确的输出,但也收到了这个错误:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    string = input().split()
EOFError: EOF when reading a line

当它使用输入进行测试时:

cars 99
quit 0

然后我没有输出。我觉得我需要在某处使用 break 语句,但我把它放在任何地方似乎都行不通。

您多次使用 input(),您可以在循环中使用一次,如果 input_string 包含“quit”,它将被终止.尝试下面的代码,它将继续接受输入,直到用户输入 quit

while True:
    input_string = input()
    if 'quit' in input_string:
        break
    else:
        a,b = input_string.split(' ')
        print(f'Eating {b} {a} a day keeps the doctor away.')

如果你想一次获取所有输入,那么找到下面的代码,它会按你的预期工作

input_string = []
while True:
    line = input()
    if 'quit' in line:
        break
    else:
        input_string.append(line)

for line in input_string:
    a,b = line.split(' ')
    print(f'Eating {b} {a} a day keeps the doctor away.')

您可以使用循环来获得相同的结果,对于行数较多或较少的文件也可以使用它。

可以使用'quit' not in variable_name作为循环的退出条件。当您测试的变量是一个替代变量时,此语句将查找“quit”作为子字符串。

将行中的单词分开 str.split() 是你的朋友。调用它之后,它 returns 一个数组。这个数组的第一个元素是对象,第二个元素是元素的数量。

mad_lib = input()

while 'quit' not in mad_lib:
    MD_list = mad_lib.split()
    thing = MD_list[0]
    integer = MD_list[1]
    print("Eating {} {} a day keeps the doctor away.".format(integer,thing))
    
    # Read the input again to process more lines
    mad_lib = input()

正如其他人指出的那样,主要障碍可能是首先拆分输入。此外,不要考虑这个练习,因为会有一定数量的字符串。字符串可以是 0 到无穷大——这将留给用户(或计算机)来决定。在循环之前和循环中 str.split() 和循环输入后,您可以使用 not in 来 KISS(保持简单愚蠢)而不是使用中断。当然,休息看起来好像你在本章的课程中专心致志,但到目前为止我发现只有在 select 情况下才需要休息(如果有的话?)。如果您的讲师对您需要在程序中使用的内容没有要求,请使用以下内容(也见于上面的@Jamal McDaniel / @Iñigo González)。

user_input = input()  #initial input

while 'quit' not in user_input:
    choices = user_input.split()  #split the string
    word = choices[0]
    integer = choices[1]
    print("Eating {} {} a day keeps the doctor away.".format(integer, word))
    user_input = input()  #get another input and loop until 'quit'