Python Forum

Full Version: loop (create variable where name is dependent on another variable)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys, i am new to python. i am coding a buy/sell order instruction for interactive brokers api. Is there a way to simplify the code here?

es_nos  = 0
spy_nos = 0
nq_nos  = 1
qqq_nos = 2
rty_nos = 3
iwm_nos = 4
zb_nos  = 5
tlt_nos = 6

es_buy_sell  = 'buy' if es_nos > 0 else 'sell'
spy_buy_sell = 'buy' if spy_nos > 0 else 'sell'
nq_buy_sell  = 'buy' if nq_nos > 0 else 'sell'
qqq_buy_sell = 'buy' if qqq_nos > 0 else 'sell'
rty_buy_sell = 'buy' if rty_nos > 0 else 'sell'
iwm_buy_sell = 'buy' if iwm_nos > 0 else 'sell'
zb_buy_sell  = 'buy' if zb_nos > 0 else 'sell'
tlt_buy_sell = 'buy' if tlt_nos > 0 else 'sell'
The code as shown doesn't do anything, so it's hard to discuss. You've created 8 new variables, but do you get anything from them? How will they be used? Couldn't you just look at the original variable?

Probably I would keep the original information in a collection (a list or a dictionary) and then loop over the elements for whatever action was intended.

share_count = {
    "es": 0,
    "spy": 0,
    "nq": 1,
    "qqq": 2,
    "rty": 3,
    "iwm": 4,
    "zb": 5,
    "tlt": 6,
    }

for product, count in share_count.items():
    # do something with them.
    if count > 0:
        print(f"{count} shares available.  Buy more {product}!")
    else:
        print(f"No {product} around.  SELL!")