Jamie Allan
Jamie Allan

Reputation: 1

Something not defined as it is under an "if"

This is my code:

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

The problem is stock_status is defined under the if so when I run the script it throws error that stock_status isn't defined. Is there any way of making it so stock_status is defined not just under that if because it needs to be there for the rest of my script to work. Thanks.

Upvotes: 0

Views: 60

Answers (1)

S.Chauhan
S.Chauhan

Reputation: 156

You can just initialize stock_status as None before the if statement:

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

Upvotes: 5

Related Questions