345243lkj 345243lkj - 1 year ago 145
Python Question

For Loop Not Respecting Continue Command

The problem I'm having is that the

command is skipping inconsistently. It skips the numerical output
but puts the incorrect
next to it. Why is this? If I make the ticker just
an input it should skip, it correctly prints an empty list
but when an invalid ticker is placed next to a valid one, the confusion starts happening.

import requests

ticker = ['aapl', 'phm', 'mmm']
ebitda = []

for i in ticker:

r_ebit = requests.get('https://query1.finance.yahoo.com/v10/finance/quoteSummary/' + i + '?formatted=true&crumb=B2JsfXH.lpf&lang=en-US&region=US&modules=incomeStatementHistory%2CcashflowStatementHistory%2CbalanceSheetHistory%2CincomeStatementHistoryQuarterly%2CcashflowStatementHistoryQuarterly%2CbalanceSheetHistoryQuarterly%2Cearnings&corsDomain=finance.yahoo.com%27')

data = r_EV.json()
data1 = r_ebit.json()

if data1['quoteSummary']['result'][0]['balanceSheetHistoryQuarterly']['balanceSheetStatements'][0].get('totalCurrentAssets') == None:
continue #skips certain ticker if no Total Current Assets available (like for PHM)

ebitda_data = data['quoteSummary']['result'][0]['financialData']
ebitda_dict = ebitda_data['ebitda']
ebitda.append(ebitda_dict['raw']) #navigates to dictionairy where ebitda is stored

ebitda_formatted = dict(zip(ticker, ebitda))

# should print {'aapl': 73961996288, 'mmm': 8618000384}
# NOT: {'aapl': 73961996288, 'phm': 8618000384}

Answer Source

The continue works just fine. You produce this list:

[73961996288, 8618000384]

However, you then zip that list with ticker, which still has 3 elements in it, including 'phm'. zip() stops when one of the iterables is empty, so you produce the following tuples:

>>> ebitda
[73961996288, 8618000384]
>>> ticker
['aapl', 'phm', 'mmm']
>>> zip(ticker, ebitda)
[('aapl', 73961996288), ('phm', 8618000384)]

If you are selectively adding ebitda values to a list, you'd also have to record what ticker values you processed:


and use that new list.

Or you could just start with an empty ebitda_formatted dictionary and add to that in the loop:

ebitda_formatted[i] = ebitda_dict['raw']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download