[Tutor] Question about loop and assigning variables

Steven D'Aprano steve at pearwood.info
Wed Apr 5 22:41:11 EDT 2017


On Wed, Apr 05, 2017 at 12:07:05PM -0700, Fazal Khan wrote:
> Hello,
> 
> Heres another newbie python question: How can I loop through some data and
> assign different variables with each loop

You don't. That's a bad idea.

Instead, you use a sequence (a tuple, or a list), and use an index:

TxTableAngle[0]  # the first item
TxTableAngle[1]  # the second item
etc.


> So this is my original code:
> 
> def BeamInfo(x):
>   for Bnum in x:
>         if plan1.IonBeamSequence[Bnum].ScanMode == 'MODULATED':
>             TxTableAngle =
> plan1.IonBeamSequence[Bnum].IonControlPointSequence[0].PatientSupportAngle
>             print(TxTableAngle)
>         else:
>             None


Let's say you succeed in doing what you want, and you have a bunch of 
variables called TxTableAngle_0, TxTableAngle_1, TxTableAngle_2, and so 
on. How do you use them?

The first problem is that you don't know if they even exist! You might 
not have *any* TxTableAngle variables at all, if x is empty, of if 
ScanMode is never MODULATED. So even

    TxTableAngle_0

might fail with a NameError exception. But even if you can guarantee 
that there is *at least one* variable, you don't know how many there 
will be! That depends on how many times the ScanMode is MODULATED. 
Perhaps there is only one, perhaps there is a thousand. How do you know 
if it is safe to refer to:

    TxTableAngle_3

or not? This rapidly becomes hard to code, difficult to write, harder to 
debug and maintain, a real nightmare.

Better is to collect the results into a list:

def BeamInfo(x):
    results = []
    for bnum in x:
        beam = plan1.IonBeamSequence[bnum]
        if beam.ScanMode == 'MODULATED':
            TxTableAngle = beam.IonControlPointSequence[0].PatientSupportAngle
            results.append(TxTableAngle)
            print(TxtTableAngle)
    return results

TxTableAngles = BeamInfo([0,1,2,3,4,5,6])

Now you know that TxTableAngles *must* exist. You can find out how many 
items there actually are:

    len(TxTableAngles)

you can grab any one specific item (provided the index actually exists):

    TxTableAngles[i]

and most importantly you can process all of the angles one after the 
other:

    for angle in TxTableAngles:
        print(angle)


-- 
Steve


More information about the Tutor mailing list