python错误:局部变量';a';分配前参考
我试图创建一个带有交互式输入的函数,告诉您脂肪酸(化合物)的“微笑”公式是什么,但我一直遇到以下错误:python错误:局部变量';a';分配前参考,python,Python,我试图创建一个带有交互式输入的函数,告诉您脂肪酸(化合物)的“微笑”公式是什么,但我一直遇到以下错误: def fatty_gen(chain_length, db_position, db_orientation): "Returns the SMILES code of the fatty acid, given its chain length, db position, db orientation" chain_length=input("What is the cha
def fatty_gen(chain_length, db_position, db_orientation):
"Returns the SMILES code of the fatty acid, given its chain length, db position, db orientation"
chain_length=input("What is the chain length/number of C?")
chain_length2=int(chain_length)
db_position = input("On which carbon does the double bond first appear")
db_position2=int(db_position)
db_orientation= input("What is the orientation of the double bond")
db_orientation2=str(db_orientation)
if db_orientation2 =="Z":
a="/C=C\\"
elif db_orientation2=="E":
a="\C=C\\"
else: a =""
return "C"*((db_position2)-1) + a + "C"*(chain_length2-db_position2-1)
<ipython-input-2-20b88ae22368> in fatty_gen(chain_length, db_position, db_orientation)
13 a="\C=C\\"
14
---> 15 return "C"*((db_position2)-1) + a + "C"*(chain_length2-db_position2-1)
16 fatty_gen(1,1,1)
UnboundLocalError: local variable 'a' referenced before assignment
def fatty\u gen(链长、分贝位置、分贝方向):
根据脂肪酸的链长、db位置和db方向,返回脂肪酸的SMILES代码
链长度=输入(“C的链长度/数量是多少?”)
链长2=int(链长)
db_位置=输入(“双键首先出现在哪个碳上”)
db_位置2=int(db_位置)
db_方向=输入(“双键的方向是什么”)
db_方向2=str(db_方向)
如果db_方向2==“Z”:
a=“/C=C\\”
elif db_方向2==“E”:
a=“\C=C\\”
else:a=“”
返回“C”*((db_位置2)-1)+a+“C”*(链长2-db_位置2-1)
脂肪根(链长、分贝位置、分贝方向)
13 a=“\C=C\\”
14
--->15返回“C”*((db_位置2)-1)+a+“C”*(链长2-db_位置2-1)
16脂肪代谢物(1,1,1)
UnboundLocalError:赋值前引用的局部变量“a”
UnboundLocalError:如果
db_orientation2
既不是“Z”
也不是“E”
变量未定义,则在赋值之前引用的局部变量“a”
您需要添加如下else
子句:
if db_orientation2 == "Z":
a = "/C=C\\"
elif db_orientation2 == "E":
a = "\C=C\\"
else:
a = "something else"
有人知道为什么反斜杠会出现两次,尽管它应该被理解为只有一个反斜杠吗?a
如果块中的非executed@MosesKoledoye在这种情况下,为什么“if/elif”在我的函数下仍然没有被执行?大概该值既不是Z也不是E。Hi,谢谢你的建议,这确实有效。但是,现在,我的输出在字符串中显示了两个反斜杠\\,而不是一个关于在python字符串中转义的阅读。或者使用原始字符串,如r'\/\/\'
if db_orientation2 =="Z":
a="/C=C\\"
elif db_orientation2=="E":
a="\C=C\\"
elif db_orientation2=="":
a="/C=C\\"
else: a=""