[Tutor] Question about loop and assigning variables

Mats Wichmann mats at wichmann.us
Wed Apr 5 21:19:42 EDT 2017


On 04/05/2017 01:07 PM, Fazal Khan wrote:
> Hello,
> 
> Heres another newbie python question: How can I loop through some data and
> assign different variables with each loop
> 
> 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
> 
> BeamInfo([0,1,2,3,4,5,6])
> 
> 
> Ideally what I want is this: when Bnum is 0, then "TxTableAngle" will be
> appended with "_0" (eg.TxTableAngle_0). When Bnum is 1 then TxTableAngle_1,
> etc. How do I do this in python?

well... what you're doing now is not very useful, as TxTableTangle goes
out of scope when the function has completed. Which means the work is
just lost.  And the else: clause - if you don't want to do anything here
(the terminology would be "pass", not "None", you don't even need to say
that).

the most likely solution, along the lines of what Alan has suggested, is
to create a list; and then you need to return it so it's actually usable
- just printing the output doesn't leave you with anything other than
characters on the console.  So consider this as a concept (not a working
implementation since there are other things missing):

def BeamInfo(x):
    TxTableAngle = []
    for Bnum in x:
        if blah :
            TxTableAngle.append(blah blah)
    return TxTableAngle

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

(of course whenever you have a create-empty-list followed by a loop of
append-to-list you can replace that by a list comprehension)

that gets you back a variable var containing a a reference to a list
("array" if you prefer to think of it that way) you can iterate over.





More information about the Tutor mailing list