代码之家  ›  专栏  ›  技术社区  ›  skysthelimit91

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

  •  0
  • skysthelimit91  · 技术社区  · 4 年前

    我想如果我知道这个问题的答案,我也许能解决这个问题。该代码只使用一组输入。但如果我输入另一个集合,它甚至不会确认它。我想如果我硬编码另一个输入()会有用,但是有没有更动态的方法来捕获输入?

    Mad LIB是一个人提供各种语言的活动, 然后用它们来完成一篇短篇小说 希望有趣)的方式。

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

    例如:如果输入为:

    apples 5
    
    shoes 2
    
    quit 0
    

    输出为:

    每天吃5个苹果可以远离医生。

    每天吃两双鞋可以远离医生。

    我的代码:

    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:比较输出0/5输出不同。见下面的亮点。

    输入

    > apples 5 
    
    > shoes 2 
    
    >quit 0 
    

    您的输出:

    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.
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Dhana D.    4 年前

    根据问题中的代码,它只接受一行输入。您需要多次编写整个代码块,或者可以利用 循环 具有 while 在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