0

I'd like to make this code better by creating a loop able to create variable depending on the item of the list

#Price for 100 
price_100 = pack['100']['product_price']
shipping_100 = pack['100']['shipment_price']
total_price_100 = price_100 + shipping_100
print(total_price_100)

#Price for 200 
price_200 = pack['200']['product_price']
shipping_200 = pack['200']['shipment_price']
total_price_200 = price_200 + shipping_200
print(total_price_200)
#etc etc etc until 1000

I thought of creating a loop like this one:

list_quantity = ['100', '200', '300', '400', '500', '600', '700', '800', '900', '1000']
for i in list_quantity:
    price = pack[i]['product_price']
#I want to create a variable called shipping + '_' + i (e.g. price_100) for each iteration
    shipping = pack[i]['shipment_price']
#Same here, a variable called shipping + '_' + i (e.g shipping_100)
    total_price = price + shipping
    print(total_price)
jjyoh
  • 428
  • 2
  • 6
  • 22
  • Use [sequence type](https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange). (I don't do Python, so I don't know which one would be suitable, but fundamentally lists and similar are how you deal with this sort of thing.) – T.J. Crowder Dec 08 '17 at 15:11
  • 2
    Dynamically creating variable names is _possible_, but it's a **really** bad idea. Instead, just use a dictionary, which lets you store stuff by name. Or if you don't really need names, store stuff by index number in a list. Or use some combination. – PM 2Ring Dec 08 '17 at 15:12
  • Alright! I'm gonna try that! thanks – jjyoh Dec 08 '17 at 15:14
  • 1
    You can create the variables with the help of `globals()` or `eval`, but I don't think it's a good idea to create variable names dynamically. Are you sure, you want it? Instead I'd recommend you to keep dictionaries for this purpose. – Fomalhaut Dec 08 '17 at 15:15

0 Answers0