如何将用户多个输入添加到列表?给定代码如何实现多输入?
Hey there! Let's tackle your questions one by one.
How to add multiple user inputs to a list
The core idea is to use a loop to keep asking for input until the user decides to stop, then add each valid input to your list. Common stop triggers include entering an empty string (just pressing Enter), or a specific keyword like "quit".
How your provided code implements multi-input functionality
Let's walk through each line of your code to understand how it works:
names = [] # Here we define an empty list. while True: eingabe = input('Please enter a name: ') if not eingabe: break names.append(eingabe) print(eingabe)
names = []: First, we create an empty list to store all the names the user inputs.while True: This sets up an infinite loop—it'll keep running until we hit abreakcommand.eingabe = input('Please enter a name: '): We prompt the user to enter a name, and store their input in theeingabevariable (that's German for "input", by the way).if not eingabe: break: We check if the input is empty (meaning the user just pressed Enter without typing anything). If that's the case, we exit the loop.names.append(eingabe): If the input isn't empty, we add the entered name to ournameslist.print(eingabe): This line just gives immediate feedback by printing the name the user just entered (it's optional, but helpful for confirming the input was received).
How to use this code
- Run the script—you'll see the prompt
Please enter a name:. - Type a name and press Enter; the name will be added to the
nameslist, and you'll see it printed back to you. - Repeat step 2 for as many names as you want to add.
- When you're done, just press Enter without typing anything—this triggers the
breakand stops the loop.
If you want to see all the names you collected at the end, you can add a line after the loop:
print("All entered names:", names)
内容的提问来源于stack exchange,提问作者Aria Bhej
相关产品推荐
相关产品推荐

