1

I have a newbie questions: let say I have this list of stock in python

import requests

list = ["AMZN","APPL", "BAC"]

try:
    for x in list:
        url ='https://financialmodelingprep.com/api/v3/quote-short/'+x+'?apikey=demo'
        response = requests.request('GET', url)
        result = response.json()
        print(result[0]["price"]) 

except:
    pass

the second ticker will throw an exceptions, how do I make python to run the third ticker no matter what happen to the second ticker requests?

Sociopath
  • 13,068
  • 19
  • 47
  • 75
  • A blanket `except` is almost always a bug. See https://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice – tripleee Aug 13 '20 at 08:00

2 Answers2

1

Use try-except inside for loop like below

import requests

list = ["AMZN","APPL", "BAC"]


for x in list:
    try:
        url ='https://financialmodelingprep.com/api/v3/quote-short/'+x+'?apikey=demo'
        response = requests.request('GET', url)
        result = response.json()
        print(result[0]["price"]) 

    except:
       pass
Sociopath
  • 13,068
  • 19
  • 47
  • 75
0

You can use continue

import requests

list = ["AMZN","APPL", "BAC"]

for x in list:
    try:
        url ='https://financialmodelingprep.com/api/v3/quote-short/'+x+'?apikey=demo'
        response = requests.request('GET', url)
        result = response.json()
        print(result[0]["price"])
    except:
        continue
Ahmet
  • 7,527
  • 3
  • 23
  • 47