How can define a new parameter in function and later use it?

Question:

I get the error: "AttributeError: ‘function’ object has no attribute ‘request_symbol’" when running my code. Can somebody explain how can i define new parameter in def and then later use it?

def request_income_statement (symbol, api_key):
    url = 'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol=' + symbol + '&apikey=' + api_key
    r = requests.get(url)
    data_IS = r.json()
    request_symbol = data_IS.get('symbol')
    return request_symbol

request_income_statement(symbol, api_key)

print(request_symbol)
Asked By: mptrsn217

||

Answers:

I would say, that you need to assign the request_symbol to a variable outside of your function.

try something like:

result = request_income_statement(symbol, api_key)
print(result)

instead of your last two lines

Answered By: foreverandthreedays

You are correctly returning a value from your function, with the last line return request_symbol

But perhaps your confusion is that only the value is returned, not the variable, i.e. the name request_symbol does not exist outside the function.

When you call the function request_income_statement(symbol, api_key) ….that statement itself returns a value (the value returned from your function), but you are currently not assigning the value to any var name.

Try this:

def request_income_statement (symbol, api_key):
    url = 'https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol=' + symbol + '&apikey=' + api_key
    r = requests.get(url)
    data_IS = r.json()
    request_symbol = data_IS.get('symbol')
    return request_symbol

myvar = request_income_statement(symbol, api_key)

print(myvar)

Do you see how the value moves between different var names now?

Of course you could also re-use the request_symbol name like:

request_symbol = request_income_statement(symbol, api_key)

print(request_symbol)

But it’s important to note that the name request_symbol outside of your function is a different variable from the one inside the function.

Answered By: Anentropic
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.