'f' strings and loop, variable that counts variables in dataframe depending on the #number of variables for excel writer and python

worksheet.write_formula('K2','= Inputs!$A$2*Inputs!$B$2*J2')
worksheet.write_formula('K3','= Inputs!$A$2*Inputs!$B$2*J3')
worksheet.write_formula('K4','= Inputs!$A$2*Inputs!$B$2*J4')
worksheet.write_formula('K5','= Inputs!$A$2*Inputs!$B$2*J5')
worksheet.write_formula('K6','= Inputs!$A$2*Inputs!$B$2*J6')
worksheet.write_formula('K7','= Inputs!$A$2*Inputs!$B$2*J7')

I want to make these a loop for a certain range in python so I do not have to write out each formula for K2-K7. Is there an easier way to do this with enumerate or a list? If so please provide an example.



Solution 1:[1]

Like this?

for i in range(2,8):
    worksheet.write_formula(f'K{i}',f'= Inputs!$A$2*Inputs!$B$2*J{i}')

Solution 2:[2]

This seems to provide the output you expect:

for i in range(2, 7+1):
    worksheet.write_formula(f'K{i}', f'= Inputs!$A$2*Inputs!$B$2*J{i}')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 3nws
Solution 2