python - 我有 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
我试过这段代码,但只有当我输入第一个月的费用时它才会运行,其余月份它不起作用。 请帮忙
解决方案
如果匹配,您想从循环中中断。这样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')
推荐阅读
- c++ - 有没有办法改变 std::pair 的引用成员指向的位置?
- haskell - 在字符串理解中将数字更改为整数
- r - 在 R Studio 中可视化自定义调色板
- assembly - GAS aarch64 语法获取 .ascii 字符串长度
- django - 如何创建视图类在 django 视图中包含所有功能
- javascript - 使用 jQuery 更新动态加载图像的 SRC 属性
- arrays - 将预处理器宏分配给数组成员时如何避免“预期表达式”错误
- php - laravel 中的 where 子句用于搜索
- javascript - getTheme() 本机基础类型
- python - sys.stdout 只创建一个空文件