skip to Main Content

I have defined a function:

def findbasecoin(Ticker):
    mycursor.execute(f"SELECT `param_basecoin`.`Symbol` FROM `param_asset` INNER JOIN `param_pair` ON `param_asset`.`id_pair` = `param_pair`.`pair_id` INNER JOIN `param_basecoin` ON `param_pair`.`Coin2_id` = `param_basecoin`.`basecoin_id` WHERE `param_asset`.`Ticker` LIKE '{Ticker.lower()}';")
    for result in mycursor:
        result = result[0]

When I do print(result), I have the expected answer : a base currency

I call this function from another place:

message= json.loads(message)
print(str(datetime.datetime.now()) + ": ")
print(message)
if message['e'].lower()=='zzztrade' : 
    basecoin = findbasecoin(message['s'])
    print(basecoin)
    forex_calc_list = {'v_usd' : 'USD', 'v_eur' : 'EUR', 'v_gbp' : 'GBP'}
    for x in forex_calc_list:
        mycursor.execute(f"SELECT `Rate`  FROM `param_forex` WHERE `Coin` LIKE '{basecoin}' AND `Basecoin` LIKE '{forex_calc_list[x]}'")
        for result in mycursor:
            print(result[0])

and I get NONE as a result when I print(basecoin) !
Why ?

3

Answers


  1. The findbasecoin() function does not have a return value, that’s why basecoin is None. (Strike as OP updated their question)

    Improvement: Iterating through the query results only to return the last one is a waste of time. You only need to ensure the query returned something useful and then return the columns you need from that row. In Python last value has index [-1].

    You could use something like:

    return cursor[-1][0] if len(cursor) and len(cursor[-1]) else []
    
    Login or Signup to reply.
  2. Try adding a return statement

    def findbasecoin(Ticker):
        mycursor.execute(f"SELECT `param_basecoin`.`Symbol` FROM `param_asset` INNER JOIN `param_pair` ON `param_asset`.`id_pair` = `param_pair`.`pair_id` INNER JOIN `param_basecoin` ON `param_pair`.`Coin2_id` = `param_basecoin`.`basecoin_id` WHERE `param_asset`.`Ticker` LIKE '{Ticker.lower()}';")
        for result in mycursor:
            result = result[0]
        return result
    

    I am not clear on why you are looping through values in mycursor, modifying the result each time. Is it satisfactory to return just the last result?

    If not, you might want to modify the code above.

    Login or Signup to reply.
  3. That’s because your function does not return a value. Also you’re mutating the loop variable while looping, your indentation is wrong and your query is prone to SQL injections. For the last issue try using prepared statements .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search