1 回答
TA贡献1794条经验 获得超8个赞
您将i变量检查为字符串 ( if i == '':),但它在前一行 ( i = int(input(prompt))) 中被强制转换为整数。您应该检查列表的长度而不是这一行:elif i != total_order[i]:。由于这个问题,您的脚本无法正常工作。我写了一个工作代码,我已经测试了它。请参阅下面我的代码/测试。
此外,您的货车会改进您的代码(例如:检查输入是否可以转换为整数。)。
代码:
def check_valid(prompt):
while True:
try:
i = input(prompt)
if not i:
print("You must enter a value for the doughnut item you would like to change.")
print()
elif int(i) > len(total_order)-1:
print("Invalid")
else:
break
except:
break
return int(i)
total_order = [['Cream', 6, 18], ['Cookies', 5, 20], ['Jam', 6, 16]]
for i in range(len(total_order)):
print("{} {} {} Doughnuts = ${:.2f}".format(i, total_order[i][1], total_order[i][0],
total_order[i][2]))
doughnuts_gone = check_valid(
"Enter the number associated with the doughnut order you would like to remove? ")
print("Valid value! Selected one: {}".format(total_order[doughnuts_gone]))
输出:
>>> python3 test.py
0 6 Cream Doughnuts = $18.00
1 5 Cookies Doughnuts = $20.00
2 6 Jam Doughnuts = $16.00
Enter the number associated with the doughnut order you would like to remove? 3
Invalid
Enter the number associated with the doughnut order you would like to remove?
You must enter a value for the doughnut item you would like to change.
Enter the number associated with the doughnut order you would like to remove? 0
Valid value! Selected one: ['Cream', 6, 18]
添加回答
举报