简体   繁体   中英

How to read from user input until newline is found in Python?

I want to take unknown number of positive and negative integer number from user. The input will stop when the user press the Enter key.

For example - If an user enter 1 2 3 4 5 -9 -10 1000 -Enter Key-
then it will store "1 2 3 4 5 -9 -10 1000"

Here is my tried code -

a = []
inp = input()

while inp != "\n":
    a.append(inp)
    inp = input()

print(a)

But this is not stop taking input even after pressing Enter Key.

Edit - This question asked for taking input until empty input but my question is taking input in one line until user press Enter button.

Just change it to

while inp:
    a.append(inp)
    inp = input()

When newline will be entered, inp is an empty string, which is falsy , thus breaking the loop.

If you are using Python 3.8, you could utilise the walrus operator here

ls = []

while (inp := input("> ")):
    ls.append(inp)

print(ls)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM