简体   繁体   中英

In Python, write a program that asks the user to type in four numbers and puts all of them in a list called lst

I've written a program that asks the user to type in four numbers like this:

a = input()
first = int(a) 
b = input() 
second = int(b) 
c = input() 
third = int(c) 
d = input() 
fourth = int(d) 

I do not understand how can I put them in a list.

You should improve your code a little bit:

first = int(input())
second = int(input())
third = int(input())
fourth = int(input())
lst = [first, second, third, fourth]

Note that you could use list-comprehension:

lst = [int (input ()) for time in range (4)]

This uses a simple for loop to execute int (input ()) 4 times. Now you could just access the inputs by using lst [0] , lst [1] , 'lst [2] , and lst [3] .

First off, you can put your code in a code block by using an empty line and then indenting 4 spaces.

You can put your variables in a list like this:

list_variables = [first, second, third, fourth]

option one :

lst = [first, second, third, fourth]

option two :

lst = []
lst.append(first)
lst.append(second)
lst.append(third)
lst.append(fourth)

One more approach is to ask input numbers separated by space and then split them

numbers = input()
numbers_list = numbers.split(' ')
int_numbers_list = map(int, numbers_list)

Possible raise error if count of numbers not equal 4

while True:
    numbers = input()
    numbers_list = numbers.split(' ')
    if len(numbers_list) != 4:
        print('Enter numbers again')
        continue
    int_numbers_list = map(int, numbers_list)
    break

Here is a 1-liner but does not take care of the 4 input restriction (in case you need):

lst = list(map(int, input().split()))

'''
3 4 5 6
[3, 4, 5, 6]    
'''                                          

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