473,405 Members | 2,282 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

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

kmartinenko
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:

Expand|Select|Wrap|Line Numbers
  1. #---Feed TranPy the csv and sys modules---
  2. import csv, sys
  3. #---Open source file, read source file, write to new source file---
  4. source = csv.reader(open("H:/transpor/Transit Ridership Database/TranPy/LoadData.csv", "rb"))
  5. for TIME, DIR, LOCATION, ON, OFF, LOAD, RUNTIME, LATITUDE, LONGITUDE, SAMPLES in source:
  6.     print TIME, DIR, LOCATION, LOAD
  7. for LOAD in source:
  8.     if LOAD>20 
  9.     print 'greater than 20'
  10. else: 
  11.     print 'less than 20'
  12. results = csv.writer(open("H:/transpor/Transit Ridership Database/TranPy/LoadData_out.csv", "wb")) 
  13. results.writerows(row)
  14.  
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!
Aug 25 '08 #1
2 1421
boxfish
469 Expert 256MB
Hi,
I'm not familiar with csv files but I'll see what I can help you with.

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:
Expand|Select|Wrap|Line Numbers
  1. for LOAD in source:
  2.     if LOAD>20:
  3.         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:
Expand|Select|Wrap|Line Numbers
  1. for TIME, DIR, LOCATION, ON, OFF, LOAD, RUNTIME, LATITUDE, LONGITUDE, SAMPLES in source:
  2.     print TIME, DIR, LOCATION, LOAD
  3.     if LOAD>20:
  4.         print 'greater than 20'
  5.     else:
  6.         print 'less than 20'
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:
Expand|Select|Wrap|Line Numbers
  1. for TIME, DIR, LOCATION, ON, OFF, LOAD, RUNTIME, LATITUDE, LONGITUDE, SAMPLES in source:
  2.     print TIME, DIR, LOCATION, LOAD
  3.     for row in LOAD:
  4.         if row>20:
  5.             print 'greater than 20'
  6.         else:
  7.             print 'less than 20'
Hope this helps.
Aug 26 '08 #2
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])

Expand|Select|Wrap|Line Numbers
  1. import csv
  2.  
  3. sourcefile = open('H:/example.csv', 'rb')
  4. outfile = open('H:/outfile.csv', 'wb')
  5.  
  6. source = csv.reader(sourcefile, dialect='excel') #tells the program what format sourcefile is in
  7. dest = csv.writer(outfile, dialect='excel') #tells the program what format the destination file is in
  8.  
  9. 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
  10.     print lst[0], lst[1], lst[2], lst[5]  # TIME, DIR, LOCATION, LOAD
  11.  
  12.     try: 
  13.         x = int(lst[5])     #define LOAD as an integer
  14.         if x >= 20:
  15.             print 'load greater than 20'
  16.             dest.writerow(lst)
  17.         else:
  18.             print 'load less than 20 -- not copied'
  19.  
  20.     except ValueError:   #error handling...if value is null or not in the correct format
  21.         print 'Cannot decide:', repr(lst)    #returns list as a parseable object
  22.  
  23. sourcefile.close() #close the sourcefile
  24. outfile.close() #close the write-to file
  25.  
Aug 26 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

34
by: Erik Johnson | last post by:
This is somewhat a NEWBIE question... My company maintains a small RDBS driven website. We currently generate HTML using PHP. I've hacked a bit in Python, and generally think it is a rather...
23
by: assaf__ | last post by:
Hello, I am beginning to work on a fairly large project and I'm considering to use python for most of the coding, but I need to make sure first that it is reliable enough. I need to make sure...
8
by: Tim Tyler | last post by:
Like C, Python seems to insist I declare functions before calling them - rather than, say, scanning to the end of the current script when it can't immediately find what function I'm referring to. ...
59
by: seberino | last post by:
I've heard 2 people complain that word 'global' is confusing. Perhaps 'modulescope' or 'module' would be better? Am I the first peope to have thought of this and suggested it? Is this a...
3
by: Steven W. Orr | last post by:
This is all an intro learning experience for me, so please feel free to explain why what I'm trying to do is not a good idea. In the Cookbook, they have a recipe for how to create global...
0
by: KA NMC | last post by:
Is is possible to nest a listview with out using a third party application? I'm able to do this in a datagrid but, it creates a datarelation link to see the nested table - will I be able to do this...
0
by: Jon Harrop | last post by:
xahlee@gmail.com wrote: This does not even start running in Mathematica 6, let alone produce any correct results. The first line was deprecated some time ago. I don't know what is wrong with the...
7
by: -Lost | last post by:
Is it possible to end the outermost function from an inner function? I've been tasked with implementing a feature check in some existing code and I wondered if this could be done: function...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.