Home > Back-end >  How can I grab multiple values that a user inputs and put them in a list without having to continuou
How can I grab multiple values that a user inputs and put them in a list without having to continuou

Time:04-07

I think if I know the answer to that question, I might be able to solve this. The code works with just one set of inputs. But if I input another set, it doesn't even acknowledge it. I think it would work if I hardcode another input() but is there a more dynamic way to capture the inputs?

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:

Eating 5 apples a day keeps the doctor away.

Eating 2 shoes a day keeps the doctor away.

My code:

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.

Input

> 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.

CodePudding user response:

By the code in your question, it accepts only ONE line of input. You need to write the whole block of code multiple times or you can utilize looping with while in python.

For example, the process you can do step by step is:

  1. Set the looping and make it infinite unless it receives quit
  2. Put the whole code block in the looping (while True) block.
  3. Add the stopping condition, i.e. when it receives quit 0.

Here's the code for the steps above.

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
  • Related