这是我的代码:
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
下定义,因为它需要在我的脚本的其余部分工作。感谢。
答案 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