我有一个家庭作业的问题,我想改进一下。这个想法是允许用户在给定一些选项的情况下“挑选一件要放入背包中的物品”。我把那部分记下来了。我想要做的是,一旦通过用户输入“选择”了列表中的项,就使用pop()函数将其从列表中删除。如何让pop()以字符串数字1-4的形式传递随机的用户输入?
我尝试将pop()中的值设置为"input()“和"itemToAdd”变量。
import sys
itemsForBackpack = ["1", "2", "3", "4"]
itemsForBackpack = ["book", "computer", "keys", "travel mug"]
while True:
print("Would you like to:")
print("1. Add an item to the backpack?")
print("2. Check if an item is in the backpack?")
print("3. Quit")
userChoice = input()
if(userChoice == "1"):
print("What item do you want to add to the backpack?" + " Select the number representing the item you wish from left to right eg '1 = book'."+ str(itemsForBackpack))
itemToAdd = input()
if itemToAdd == "1":
print(str(itemsForBackpack[0]))
elif itemToAdd == "2":
print(str(itemsForBackpack[1]))
elif itemToAdd == "3":
print(str(itemsForBackpack[2]))
elif itemToAdd == "4":
print(str(itemsForBackpack[3]))
return_value = itemsForBackpack.pop()
print('return_value: ', return_value)
print("Updated List: ", itemsForBackpack)
break
if(userChoice == "2"):
print("What item do you want to check to see if it is in the backpack?")
itemToCheck = input()
我想它需要一个整数,因为我得到一个错误,说字符串不能显示为整数。
https://stackoverflow.com/questions/56518694
复制相似问题