Search code examples
pythonpython-3.xgoogle-colaboratory

Currently getting an error TypeError: can only concatenate str (not "NoneType") to str


Traceback (most recent call last):  
  File "<ipython-input-21-0cdf2cfacf71>", line 335, in <module>  
    + my_value_a  
TypeError: can only concatenate str (not "NoneType") to str  

Can anyone help with this error?

Code

def get_env_var(i):
    try:
        letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'][i // 50]
        return os.getenv("MY_VAR_" + letter)
    except IndexError:
        return "demo"


for i in range(0, len(mySymbols)):
    try:
        my_value_a = get_env_var(i)
        #my_value_a = "demo"
        #my_value_a =  os.getenv("MY_VAR_K")
        url_is_y = (
            "https://financialmodelingprep.com/api/v3/financials/income-statement/"
            + mySymbols[i]
            + "?apikey="
            + my_value_a
        )
        url_bs_y = (
            

Solution

  • So if the key for os.getenv() is invalid, it returns the default values that you pass as the second parameter. If you don't set this default value, it returns a None. Possible Fixes:

    def get_env_var(i):
        try:
            letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'][i // 50]
            return os.getenv("MY_VAR_" + letter, "demo")
        except IndexError:
            return "demo"
    

    This will return the "demo" string if an invalid key is encountered. Or you can do this if the output is acceptable:

    for i in range(0, len(mySymbols)):
        try:
            my_value_a = get_env_var(i)
            #my_value_a = "demo"
            #my_value_a =  os.getenv("MY_VAR_K")
            url_is_y = (
                "https://financialmodelingprep.com/api/v3/financials/income-statement/"
                + mySymbols[i]
                + "?apikey="
                + str(my_value_a) # This will convert None to 'None'
            )
            url_bs_y = (
    

    Check this page out for more info and examples on how this function works.