[Tutor] Problems with iterations and breaking loops.

Karjer Jdfjdf karper12345 at yahoo.com
Wed Mar 17 16:02:07 CET 2010


I'm having problems with iterations and loops. So I'm curious about the best Python-way to do iterations of lists (in if, while etc statements) and breaking of loops.

I have a list of tuples with 2 values. I want to perform calculations on all of these for each value in a range of values (e.g. 100 to 110).


list_of_tuples = [(90629, 4644), (90706, 4617), (90729, 4709)]

#start value
n = 100
#maximum value
nmax = 110

#First I create a list for the values
range_list = []
while n < int(nmax+1):
    range_list.append(n)
    n = n + 1

print range_list


for i in range_list:
    for t in list_of_tuples:
        val1 = t[0]
        val2 = t[1]
        print "do stuff with\t" + str(val1) + '\t' + str(val2) + \
              '\tfor rangevalue\t' + str(i)

But I think that the rangelist is not needed and it can be done better (and faster for large quantities of data). I think it's better to have somethng like the code below. But I'm having problems with breaking the second loop and returning to the first loop. If I put in another while-statement befor the for-statement it stops after 1 run and it has to continue until the end of the range.

while n < int(nmax + 1):
    #create new variable to count in 2nd loop
    n1 = n
    print '\n'

    for t in list_of_tuples:
        val1 = t[0]
        val2 = t[1]
        print "do stuff with\t" + str(val1) + '\t' + str(val2) + \
              '\tfor range\t' + str(n1)
        n1 = n1 + 1





      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100317/93869958/attachment.html>


More information about the Tutor mailing list