[Tutor] calling a variable name

Alan Gauld alan.gauld at btinternet.com
Mon Oct 22 09:38:59 CEST 2007

"Bryan Fodness" <bryan.fodness at gmail.com> wrote

>I want to get a variable name dependent on another variable.

Thats usually a bad idea, but...

> I have tried,
> 'fs' + str(int(round(unblockedFS))) for fs13

I have no idea what you think this will do.
It gives a syntax error for me, which is what I expected.

> and I get an invalid literal.

Can you post real code and real error messages please?

> If I code in the fs13, everything works. Is
> it possible to do this?

I'm not sure because I'm not sure what you are really
trying to do. Creating new variable names on the fly
is usually not the best approach but without a context
we can't offer an alternative. The code snippet above
is no help since it is not valid Python.

> unblockedFS=13.4
> for line in file('21Ex6MV_tmr.dat'):
>    d, fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9, fs10, fs11, fs12, 
> fs13,
> fs14, fs15, fs16, fs17, fs18 = line.split()

BTW, Since all your variables are of the form fsNN it is probably
as easy(and less typing) to do:

fs = line.split()

and just refer to them  by index (extracting d if required):

>    if float(d) == round(calc_depth):

      if float(fs[0]) == round(calc_depth)
>        b = float(fs13)

          b = float(fs[13])


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list