没有定义的东西是“if”

时间:2017-11-02 22:49:23

标签: python python-3.x

这是我的代码:

if "stockStatus" in res.text:
  data = json.loads(res.text)
  stock_status = data["stockStatus"]
  name = data["name"]
  prod_url = data["URL"]

else:
 print("Product not yet loaded or removed: " + pid)
 pass

if stock_status == "IN STOCK":
 #rest of code

问题是stock_status是在if下定义的,因此当我运行脚本时,它会抛出stock_status未定义的错误。是否有任何方法可以使stock_status不仅仅在if下定义,因为它需要在我的脚本的其余部分工作。感谢。

1 个答案:

答案 0 :(得分:5)

您可以在if语句之前将stock_status初始化为None

stock_status = None

if "stockStatus" in res.text:
    data = json.loads(res.text)
    stock_status = data["stockStatus"]
    name = data["name"]
    prod_url = data["URL"]
else:
    print("Product not yet loaded or removed: " + pid)
    pass

if stock_status == "IN STOCK":
    #rest of code