简体   繁体   中英

Assigning numbers via user input in list as integer in Python

here's the program

assignments = (input(“assignments:”).split(",") #enter number separeted by comma
print(type(assignments[0]))

output is class str

how to save the numbers as integers not as string,
I have tried

assignments = int(input("assignments:")).split(",")

but it gives me error

ValueError: invalid literal for int() with base 10: #numbers which I enter

You cannot cast the entire list (or the input string that contains all the commas) to int as a whole, you would have to do it for the split tokens individually, eg with a list comprehension :

assignments = [int(x) for x in input(“assignments:”).split(",")]

or using map :

assignments = list(map(int, input(“assignments:”).split(",")))

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