python - Python - 为什么条件在一个函数中执行但在另一个函数中不执行?
问题描述
我是 Python 初学者。我正在尝试编写一些基本代码来自动化一个简单但重复的工作过程,但被这个问题难住了。
# Prior to the code block below, a csv file import would have created the a and ag variables with their respective numerical values.
high = list(range(66, 99))
mod = list(range(36, 65))
low = list(range(1,35))
verysiggap = list(range(61, 99))
siggap = list(range(31, 60))
nonsiggap = list(range(1, 30))
fco_output_list = []
def fco_block1(*args):
if a in high and ag in high:
print("Both a and ag are high!")
fco_output_list.append("fco1")
if a in high and ag in high and a-ag in nonsiggap:
fco_output_list.append("foc2")
fco_block1(a, ag)
a_ag_combi_output = 0
a_ag_gap_output = 0
def fco_block2(*args):
global a_ag_combi_output
if a in high and ag in high:
a_ag_combi_output = 0
elif a in high and ag in low or ag in mod:
a_ag_combi_output = 1
elif a in mod and ag in low:
a_ag_combi_output = 2
elif ag in high and a in low or a in mod:
a_ag_combi_output = 3
elif ag in mod and a in low:
a_ag_combi_output = 4
elif a in low and ag in low:
a_ag_combi_output = 5
global a_ag_gap_output
if a in high and ag in high and a-ag in nonsiggap:
a_ag_gap_output = 1
fco_block2(a, ag)
# There are some simple print functions after the code above that tell me very clearly that fco_block2 executed without any issues.
至于 fco_block1 的执行,没有错误消息,但条件似乎没有执行。根据 a 和 ag 的导入值,fco_output_list 应该已由 fco1 和 fco2 填充,但事实并非如此。
为什么会这样?我觉得这很奇怪,特别是当 block1 中的条件语句与 block2 中的相应条件语句的措辞相同时,但是 block2 中的条件被执行而不是 block1 中的条件?
解决方案
您的问题似乎与您定义“高”列表的方式有关。
根据您的评论:“我用同一个 csv 文件(其中 a = 99,ag = 86)运行了无数次”
在 Python 中,“范围”的结束值是排他性的(即最多但不包括),这意味着“列表(范围(66, 99))”将以 98 结束。为了清楚起见,这些都是“高”名单:
[66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]
如您所见,99 不存在。因此,例如, (a = 99, ag = 86) 将失败,因为 a 不在“高”状态。
我用 (a = 70, ag = 67) 测试了你的代码,它打印出“a 和 ag 都很高!”
如果要(a = 99, ag = 86)触发 fco_block1 中的 print 语句,将 high 改为
high = list(range(66, 100))
推荐阅读
- node.js - Mongoose 中的深度 find() 查询
- ios - 更改模态视图控制器的大小
- ruby-on-rails - 错误 422 无法处理的实体 - Rails API VueJS 来自
- python - 将 pandas DataFrame 中每一行的最后一个非零值转换为 0
- unity3d - 如何判断一个对象是预制资产还是该预制的实例?
- go - 奇怪的 404 服务器错误 (ListenAndServeTLS)
- go - 内存中的数据以最小化数据库读取?
- python - Python 阶乘程序 - 打印方程
- python - 程序忽略“else”语句
- reactjs - 将数据从孩子传递给父母