简体   繁体   中英

How do I have a user input a list?

I need to have users input a list for my program in order for it to work properly, and the list needs to be formatted like [1,1,2]. This is the code gathering the list input:

entry = list(input(": "))

I was having some problems and put it through a debugger and saw that the list was showing up as this: 在此处输入图片说明

How can I make it work correctly?

While its possible to evaluate a list like that, it's not good practice as evaluating anything can introduce many edge cases.

A better solution would be to have the user input the values of the list either all at once:

entry = list(input("Enter the values: ").split(","))
# User enters: 1,2,3,4,5
# List ends up as: [1, 2, 3, 4, 5]

or one at a time

endChar = '$' # Setting end character
in = '' # Clearing user input variable
chars = [] # List of values
print("Enter your values, use '$' to finish.") # User prompt
while in != endChar: # Continue until $ is entered
    in = input("Value: ") # Get value
    chars.append(in) # Add element to list
print(chars) # Finished list

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