Is it possible to nest 'for' statements in Python?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kmartinenko
    New Member
    • Jan 2008
    • 12

    Is it possible to nest 'for' statements in Python?

    Hi,

    I am very new to Python and I would like to know if it is possible to nest 'for' statements?

    The question precipitates from a certain problem I am having with running a simple calculation on a column in a .csv file. I want to read columns from an existing .csv file and write out selected columns from the .csv file along with the new column containing the results from the calculation to a new .csv file.

    I am thinking the way to do this is to nest for statements so that I am first reading the desired columns, performing an if else statement on the column, and then writing out the results using another for statement.

    Maybe I am making this out to be more complicated than it has to be. Like I said, I am new...I am probably missing a crucial step. Here is what I have so far:

    Code:
    #---Feed TranPy the csv and sys modules---
    import csv, sys
    #---Open source file, read source file, write to new source file---
    source = csv.reader(open("H:/transpor/Transit Ridership Database/TranPy/LoadData.csv", "rb"))
    for TIME, DIR, LOCATION, ON, OFF, LOAD, RUNTIME, LATITUDE, LONGITUDE, SAMPLES in source:
        print TIME, DIR, LOCATION, LOAD
    for LOAD in source:
        if LOAD>20 
        print 'greater than 20'
    else: 
        print 'less than 20'
    results = csv.writer(open("H:/transpor/Transit Ridership Database/TranPy/LoadData_out.csv", "wb")) 
    results.writerows(row)
    1) I am getting an invalid syntax error at 'if LOAD>20'
    2) How do I pass this calculation to the results so that it prints a 'greater than 20/less than 20' statement for each row in the column LOAD based upon its value?

    Thanks for the help!
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    Hi,
    I'm not familiar with csv files but I'll see what I can help you with.

    Originally posted by kmartinenko
    I am getting an invalid syntax error at 'if LOAD>20'
    Good, that one's not too hard; you need a colon after the if, and the print statement has to be indented, like this:
    Code:
    for LOAD in source:
        if LOAD>20:
            print 'greater than 20'
    I don't think that second for loop works, because you won't get just the LOAD columns. I think that loop will be looking at all the columns in source and calling them LOAD. How about putting the code in that second for loop inside of the first for loop, like this:
    Code:
    for TIME, DIR, LOCATION, ON, OFF, LOAD, RUNTIME, LATITUDE, LONGITUDE, SAMPLES in source:
        print TIME, DIR, LOCATION, LOAD
        if LOAD>20:
            print 'greater than 20'
        else:
            print 'less than 20'
    Originally posted by kmartinenko
    How do I pass this calculation to the results so that it prints a 'greater than 20/less than 20' statement for each row in the column LOAD based upon its value?
    You should be able to iterate through LOAD with a nested for loop, like this:
    Code:
    for TIME, DIR, LOCATION, ON, OFF, LOAD, RUNTIME, LATITUDE, LONGITUDE, SAMPLES in source:
        print TIME, DIR, LOCATION, LOAD
        for row in LOAD:
            if row>20:
                print 'greater than 20'
            else:
                print 'less than 20'
    Hope this helps.

    Comment

    • kmartinenko
      New Member
      • Jan 2008
      • 12

      #3
      Thanks Boxfish...

      However, it appears as though Python does not automatically "recognize" that the value of 'LOAD' is an integer. I have done some more digging and question asking on other forums, and the consensus seems to be that I first need to identify the values of the csv in matrix format, define it as a list, and then define the value of lst[5] as an integer. I can then run the "greater than, less than" statement on LOAD (lst[5])

      Code:
      import csv
       
      sourcefile = open('H:/example.csv', 'rb')
      outfile = open('H:/outfile.csv', 'wb')
       
      source = csv.reader(sourcefile, dialect='excel') #tells the program what format sourcefile is in
      dest = csv.writer(outfile, dialect='excel') #tells the program what format the destination file is in
       
      for lst in source:  #define csv file as a matrix, Python starts at zero.  Columns are skipped, hence, LOAD is column 5, not column 3
          print lst[0], lst[1], lst[2], lst[5]  # TIME, DIR, LOCATION, LOAD
       
          try: 
              x = int(lst[5])     #define LOAD as an integer
              if x >= 20:
                  print 'load greater than 20'
                  dest.writerow(lst)
              else:
                  print 'load less than 20 -- not copied'
       
          except ValueError:   #error handling...if value is null or not in the correct format
              print 'Cannot decide:', repr(lst)    #returns list as a parseable object
                  
      sourcefile.close() #close the sourcefile
      outfile.close() #close the write-to file

      Comment

      Working...