首页 > 解决方案 > 我有 2 个清单(月份和费用的名称)。我必须输入用户的费用并告诉具有相同费用的月份名称

问题描述

month_list = ["January","Februarty","March","April","May"]
expense_list = [2340, 2500, 2100, 3100, 2980]
exp = int(input("Enter your expense:"))
for i in range(5):
    if exp == expense_list[i]:
        print('Your expense matches with the month of',month_list[i])
    else:
        print('Your expense does not matches with the list')
        break

我试过这段代码,但只有当我输入第一个月的费用时它才会运行,其余月份它不起作用。 请帮忙

标签: python

解决方案


如果匹配,您想从循环中中断。这样else如果没有匹配将执行。利用:

month_list = ["January","Februarty","March","April","May"]
expense_list = [2340, 2500, 2100, 3100, 2980]
exp=int(input("Enter your expense:"))
for i in range(5):
 if exp==expense_list[i]:
  print('Your expense matches with the month of',month_list[i])
  break
else:
  print('Your expense does not matches with the list')

更好的方法:

for x, y in zip(month_list, expense_list):
    if y == exp:
        print('Your expense matches with the month of ', x)
        break
else:
    print('Your expense does not matches with the list')

推荐阅读