简体   繁体   中英

How to take several lines as input in python?

I know the easiest way to take input in python is with the function input() .

However, what if I have to take several numbers on separate lines at once and add them up.

Example input:

2
3
1
4

How can I read this input into a list?

I am a beginner in python so please any advice is appreciated

You can do something like this:

numbers_list = []
for i in range(number_of_needs):
    n = input()
    number_list.append(n)

or you can use while if you don't know the count.

numbers_list = []
while True:
    n = input()
    if n == 'q':
        break
    number_list.append(n)

in this case, it breaks when user inputs q .

also, note that n s are String you can use int() to convert them to an integer.

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