如何获取用户输入的多个值并将它们放入列表中,而不必连续编写 input()?

How can I grab multiple values that a user inputs and put them in a list without having to continuously write input()?

我想如果我知道那个问题的答案,我也许能解决这个问题。该代码仅适用于一组输入。但如果我输入另一组,它甚至不承认。我认为如果我对另一个 input() 进行硬编码会起作用,但是是否有更动态的方式来捕获输入?

Mad Libs are activities that have a person provide various words, which are then used to complete a short story in unexpected (and hopefully funny) ways.

Write a program that takes a string and an integer as input, and outputs a sentence using the input values as shown in the example below. The program repeats until the input string is quit and disregards the integer input that follows.

Ex: If the input is:

apples 5

shoes 2

quit 0

the output is:

一天吃5个苹果,医生远离我

一天吃2双鞋,医生远离我

我的代码:

UserEntered = input()


makeList = UserEntered.split()

get_item_1 = makeList[slice(0,1)][0]
get_item_2 = makeList[slice(1,2)][0]

if "quit" not in makeList:
    print("Eating {} {} a day keeps the doctor away.".format(get_item_2,get_item_1))

1: Compare output 0 / 5 Output differs. See highlights below.

输入

> apples 5 

> shoes 2 

>quit 0 

Your output:

Eating 5 apples a day keeps the doctor away. 

Expected output:

Eating 5 apples a day keeps the doctor away. 

Eating 2 shoes a day keeps the doctor away.

根据你问题中的代码,它只接受一行输入。您需要多次编写整个代码块,或者您可以使用 looping with while in python.

例如,您可以逐步执行的过程是:

  1. 设置循环并使其无限循环,除非它收到 quit
  2. 将整个代码块放入循环 (while True) 块中。
  3. 添加停止条件,即接收到quit 0.

这是上述步骤的代码。

while True:    # Make an infinite loop.
    # Put the whole block to make sure it repeats
    makeList = UserEntered.split()
    get_item_1 = makeList[slice(0,1)][0]
    get_item_2 = makeList[slice(1,2)][0]
    
    # Print when the input is not `quit 0`
    if "quit" not in makeList:
        print("Eating {} {} a day keeps the doctor away.".format(get_item_2,get_item_1))

    # Stopping control/condition here, when it receives `quit 0`
    else:
        break