我遇到一个问题,用户输入各种代码,进入1变量,然后我想拆分这些输入使其成为一个列表。但是,我已经意识到我的变量只接受最后一个输入意味着列表只出现一个代码,而不是几个代码。如何使变量存储多个输入?
while True:
itemsneeded = input("How many items do you need?")
if itemsneeded.isnumeric() and int(itemsneeded) <= 5:
break
GTIN = ''
count = 0
while count < int(itemsneeded):
GTIN = (input('Please enter all GTIN-8 for all items'))
if GTIN.isnumeric() and len(GTIN) == 8:
Num0 = int(GTIN[0]) * 3
Num1 = int(GTIN[1])
Num2 = int(GTIN[2]) * 3
Num3 = int(GTIN[3])
Num4 = int(GTIN[4]) * 3
Num5 = int(GTIN[5])
Num6 = int(GTIN[6]) * 3
Num7 = int(GTIN[7])
total2 = (Num0 + Num1 + Num2 + Num3 + Num4 + Num5 + Num6 + Num7)
if total2 % 10 == 0:
print(GTIN)
if GTIN in open('read_it.txt').read():
print('entered GTIN is valid')
else:
print('The code entered is invalid')
print('Please renter this code')
count += 1
else:
print("The entered GTIN-8 codes are incorrect")
print(GTIN)
lst = GTIN.split()
print(lst)
我不能使用它(Two values from one input in python?)因为我不知道用户想要多少项,用户输入可以从1项到5项不等。
答案 0 :(得分:1)
创建一个空列表,然后在循环中使用list.append
。这样做是将每个新条目添加到列表的末尾。
GTIN=''
#count=0
items = [] # replaces count = 0
#while count<int(itemsneeded):
while len(items) < int(itemsneeded): # replaces other while condition
...
...
#count += 1
items.append(GTIN) # replaces count += 1
...
print(items)
在覆盖内置列表方法时,您还应该避免使用list
作为变量名。
此外,您的代码对无效输入也不起作用。如果他们输入的代码不正确,那么它仍然会增加,就像添加了有效项目一样。您应该将items.append(GTIN)
移到if语句中,检查GTIN是否有效。
答案 1 :(得分:0)
也许它会对你有所帮助:
nums = input().split()
int_nums = [ int(x) for x in nums ]