Re: [Tutor] break and exit
On 21/11/14 04:10, James Rieve wrote: I accidently used 'exit' in a loop where I meant to use 'break' and, in that case, the program seemed to work as expected but in some cases 'exit' seems to behave differently from 'break'. For example, in this code snippet using 'exit' or 'break' produces the same result: for i in range(10): if i > 3: exit else: print(i) print('out of loop') Only superficially. When you use exit Python doesn't do anything. But it repeats that non operation for every number in your range(). When you use break it is only executed once and Python leaves the for loop immediately. So although what is printed is the same the results in terms of the work Pyhon does is very different. You can demonstrate that by adding another print message for i in range(10): if i > 3: exit print("I didn't expect this!") else: print(i) print('out of loop') Now swap exit and break. for i in range(10): if i > 3: break # try using exit here. else: print(i) else: print('for loop else statement') print('out of loop') Because the for/else is only executed if the loop completes normally - which it does with exit - so a break will bypass that for/else clause. Does anyone have any pointers to descriptions of 'exit', what it is, Its the name of a function. So using it in isolation like that has the same effect as just putting any variable name on its own does: for n in range(5): n else: print('loop completed') The use of n here is like your use of exit. Its just a name. But if you called exit using () the effect would be quite different to break. It would then exit your whole program. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my phopto-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break and exit
James Rieve wrote: > I accidently used 'exit' in a loop where I meant to use 'break' and, in > that case, the program seemed to work as expected but in some cases 'exit' > seems to behave differently from 'break'. For example, in this code > snippet using 'exit' or 'break' produces the same result: > > for i in range(10): > if i > 3: > exit > else: > print(i) > print('out of loop') > > But in this case they behave differently: > > for i in range(10): > if i > 3: > break # try using exit here. > else: > print(i) > else: > print('for loop else statement') > > print('out of loop') > > Does anyone have any pointers to descriptions of 'exit', what it is, what > it means, how It's used, etc.? exit is not part of Python's syntax, it is (almost, see below) a normal function. Writing exit has no effect, instead of > for i in range(10): > if i > 3: > exit > else: > print(i) > print('out of loop') you could have written for i in range(10): if i > 3: pass else: print(i) print('out of loop') but if you invoke exit like a function > for i in range(10): > if i > 3: exit() > else: > print(i) > print('out of loop') the script will be terminated -- you can detect that by the fact that out of loop is not printed. Personally, I hardly ever use exit (or sys.exit() or `raise SystemExit`). If you want a script to stop in the middle of execution I recommend that instead of print("some code") if some_condition: exit() print("more code") you write print("some code") if not some_condition: print("more code") or (even better for all but tiny scripts) use a main function like so: def main(): print("some code") if some_condition: return print("more code") if __name__ == "__main__": main() Now -- what actually is exit? Let's fire up the interactive interpreter: $ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit Use exit() or Ctrl-D (i.e. EOF) to exit >>> help(exit) Help on Quitter in module _sitebuiltins object: class Quitter(builtins.object) | Methods defined here: | | __call__(self, code=None) | | __init__(self, name, eof) | | __repr__(self) | | -- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) So exit is an instance of Quitter. The Quitter class has a __call__ method which is executed when you invoke an instance like a function. Let's have a look a the code: >>> import inspect >>> print(inspect.getsource(exit.__call__)) def __call__(self, code=None): # Shells like IDLE catch the SystemExit, but listen when their # stdin wrapper is closed. try: sys.stdin.close() except: pass raise SystemExit(code) So exit() tries to close sys.stdin and then raises a SystemExit exception. Unless you catch that exception the program ends. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] break and exit
I accidently used 'exit' in a loop where I meant to use 'break' and, in that case, the program seemed to work as expected but in some cases 'exit' seems to behave differently from 'break'. For example, in this code snippet using 'exit' or 'break' produces the same result: for i in range(10): if i > 3: exit else: print(i) print('out of loop') But in this case they behave differently: for i in range(10): if i > 3: break # try using exit here. else: print(i) else: print('for loop else statement') print('out of loop') Does anyone have any pointers to descriptions of 'exit', what it is, what it means, how It's used, etc.? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Break outside the loop error (line 23)
On 31/05/14 10:23, Sasi - wrote: Hi, i tried to make a code to execute the functions that i described below. However i got a break outside the loop error Always post the full error message it usually contains lots of useful detail. ## Created the lists for brain and plasma before searching for common bioseq. while True: count1 += 1 s1=file1.readline().partition(',')[0] if s1 and count1 > 1: This line is not indented so the loop stops on the previous line. brain.append(s1) if not s1: break But your 'break' is here so it is outside the loop. You need to indent the whole section from if s1 and count1 > 1: so that it is inside the loop. while True: count2 += 1 s2=file2.readline().partition(',')[0] if s2 and count2 > 1: plasma.append(s2) if not s2: break And the same problem here. The indentation defines what is inside the loop. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Break outside the loop error (line 23)
On 31.05.2014 11:23, Sasi - wrote: Hi, i tried to make a code to execute the functions that i described below. However i got a break outside the loop error and i have tried to tab and all that but i still get the same error for line 23. I'm using python 2.7 Hi, as a general rule, copy paste the traceback of the actual python exception instead of summarizing it. In this specific case the error is obvious though (see below). Please help me. I'm completely new to coding (just started last week) Thank you for your time, i have pasted the code below. ## open both files file1 = open('human_brain_proteins.csv') file2 = open('human_plasma_proteins.csv') #file1 = open('log1') #file2 = open('log2') ## createdd a counter to count lines count1 = 0 count2 = 0 ## define 3 lists to be filled in later common = list() brain = list() plasma = list() ## Created the lists for brain and plasma before searching for common bioseq. while True: count1 += 1 s1=file1.readline().partition(',')[0] your while loop ends here because the next line is not indented (probably not what you intended). if s1 and count1 > 1: brain.append(s1) if not s1: break since you are not inside the while loop anymore, there is nothing to break from. while True: count2 += 1 s2=file2.readline().partition(',')[0] if s2 and count2 > 1: plasma.append(s2) if not s2: break ## Compared the lists to find out common bioseq., add the common bioseq. into the common list, ## then remove the common bioseq. from both lists for item1 in brain: for item2 in plasma: if item1 == item2: common.append(item1) brain.remove(item1) plasma.remove(item2) ## closed both files file1.close() file2.close() ## print out the lists print "Common biosequence:" print common,"\n" print "Brain specific biosequence:" print brain,"\n" print "Plasma specific biosequence:" print plasma,"\n" additional suggestion: read about the set datatype of python and its intersection and difference methods (https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset). It looks like handling your data as two sets instead of two lists should be much more convenient. Best, Wolfgang ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Break outside the loop error (line 23)
Hi, i tried to make a code to execute the functions that i described below. However i got a break outside the loop error and i have tried to tab and all that but i still get the same error for line 23. I'm using python 2.7 Please help me. I'm completely new to coding (just started last week)Thank you for your time, i have pasted the code below. ## open both filesfile1 = open('human_brain_proteins.csv')file2 = open('human_plasma_proteins.csv')#file1 = open('log1')#file2 = open('log2') ## createdd a counter to count linescount1 = 0count2 = 0 ## define 3 lists to be filled in latercommon = list()brain = list()plasma = list() ## Created the lists for brain and plasma before searching for common bioseq.while True:count1 += 1s1=file1.readline().partition(',')[0]if s1 and count1 > 1:brain.append(s1)if not s1: breakwhile True:count2 += 1s2=file2.readline().partition(',')[0]if s2 and count2 > 1:plasma.append(s2)if not s2:break ## Compared the lists to find out common bioseq., add the common bioseq. into the common list,## then remove the common bioseq. from both listsfor item1 in brain:for item2 in plasma:if item1 == item2: common.append(item1)brain.remove(item1) plasma.remove(item2) ## closed both filesfile1.close()file2.close() ## print out the listsprint "Common biosequence:"print common,"\n"print "Brain specific biosequence:"print brain,"\n"print "Plasma specific biosequence:"print plasma,"\n" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break
On 03/14/2013 07:23 PM, Matthew Ngaha wrote: if Enemy.ships: for missile in self.missiles: flag = False for rect in Enemy.rects: assert(!flag) if QPoint(missile.x + 5, missile.y) in rect: explosion = Explosion(rect.x(), rect.y()) self.explosions.append(explosion) flag = True break im about to try the suggestions. i on python 3 and this line is giving me a syntax error assert(!flag). My mistake. The exclamation point is from C. In Python, it should be "not" assert(not flag) This statement simply asserts (claims) that flag is NOT TRUE, and if for some reason it is true, it throws an exception. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break
On 03/14/2013 08:45 PM, Matthew Ngaha wrote: thanks guys ive finally got it working. even though i didnt use the flag due to invalid syntax i realized since i was getting no errors i wasnt actually doing anything wrong. My mistake was i removed the ememy ship but for some reason forgot to remove the missile so it was still active on the next update/mainloop. im still interested in finding out how to write this in python 3 assert(!flag). assert(not flag) -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break
thanks guys ive finally got it working. even though i didnt use the flag due to invalid syntax i realized since i was getting no errors i wasnt actually doing anything wrong. My mistake was i removed the ememy ship but for some reason forgot to remove the missile so it was still active on the next update/mainloop. im still interested in finding out how to write this in python 3 assert(!flag). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break
On 03/14/2013 08:08 PM, Matthew Ngaha wrote: One good approach is to have a separate function or method with >> both loops: >> >> def attack(self, Enemy): >> >> for missile in self.missiles: >> for rect in Enemy.rects: >> if QPoint(missile.x + 5, missile.y) in rect: >> explosion = Explosion(rect.x(), rect.y()) >> self.explosions.append(explosion) >> return > > i altered this because once it returns the outer loop also stops and i > need it incase i have more than 1 missile to loop through. i made it > so i did the outer loop in the program and sent the inner loop to this > function, but for some reason the code seems to break my program.. no > errors are returned but it just freezes on inputs and missile > collision. Sorry, reading failure on my part. The code you had originally should break properly. You can add assert(not flag) as Dave suggested to figure out what actually happens. Maybe you have more than one instance of the same missile? -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Children begin by loving their parents; after a time they judge them; rarely, if ever, do they forgive them. Oscar Wilde ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break
> One good approach is to have a separate function or method with > both loops: > > def attack(self, Enemy): > > for missile in self.missiles: > for rect in Enemy.rects: > if QPoint(missile.x + 5, missile.y) in rect: > explosion = Explosion(rect.x(), rect.y()) > self.explosions.append(explosion) > return i altered this because once it returns the outer loop also stops and i need it incase i have more than 1 missile to loop through. i made it so i did the outer loop in the program and sent the inner loop to this function, but for some reason the code seems to break my program.. no errors are returned but it just freezes on inputs and missile collision. > You could also set a flag and check it at the end of outer loop > and have a second break statement when the flag is set. > im trying to figure out this technique with flags but i havent got it yet.. what does a flag stand for? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break
>> if Enemy.ships: >> for missile in self.missiles: > >flag = False >> >> for rect in Enemy.rects: > >assert(!flag) > >> if QPoint(missile.x + 5, missile.y) in rect: >> explosion = Explosion(rect.x(), rect.y()) >> self.explosions.append(explosion) > >flag = True >> >> break im about to try the suggestions. i on python 3 and this line is giving me a syntax error assert(!flag). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break
On 03/14/2013 06:38 PM, Matthew Ngaha wrote: i cant seem to break out of this loop. let me explain the variables you see: if Enemy.ships: for missile in self.missiles: flag = False for rect in Enemy.rects: assert(!flag) if QPoint(missile.x + 5, missile.y) in rect: explosion = Explosion(rect.x(), rect.y()) self.explosions.append(explosion) flag = True break (untested) With that added code, if the break ever fails, it will raise an exception that you can then figure out. At that point, you can figure out why your Python executable got corrupted. more likely, you'll find that some other loop is similar enough that you got this one confused with that one. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] break
On 03/14/2013 06:38 PM, Matthew Ngaha wrote: i cant seem to break out of this loop. let me explain the variables you see: > > Enemy.ships = [] #an Enemy class variable that contains enemy ships > self.missiles = [] an instance variable that appends how many Visible > missiles my ship has fired > Enemy.rects = [] an Enemy class variable that represents a rectangle > for every ship in Enemy.ships > Explosion() = a class where explosions occur > QPoint() = is a pyqt function that takes a point x, y position as arguments > > im trying to destroy the ships if they hit a missile, even though i > use pyqt this is mainly python code > > if Enemy.ships: > for missile in self.missiles: > for rect in Enemy.rects: > if QPoint(missile.x + 5, missile.y) in rect: > explosion = Explosion(rect.x(), rect.y()) > self.explosions.append(explosion) > break > > once the missile has hit 1 Enemy.rect i want to break and go to the > next missile so the missile is destroyed and doesnt hit another Enemy, > but for some reason the break i have isnt working and the same missile > sometimes is hitting 2 different rects on the same iteration. i have > done the same loop using a simple print statements on strings greater > than a certain length and it breaks correctly. anyone have any ideas > why the break isnt breaking out of the nested/inner loop but instead > continuing to loop through the Enemies? > Yes, break statement exits only the current loop, not all loops. One good approach is to have a separate function or method with both loops: def attack(self, Enemy): for missile in self.missiles: for rect in Enemy.rects: if QPoint(missile.x + 5, missile.y) in rect: explosion = Explosion(rect.x(), rect.y()) self.explosions.append(explosion) return You could also set a flag and check it at the end of outer loop and have a second break statement when the flag is set. HTH, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Fanaticism consists of redoubling your effort when you have forgotten your aim. George Santayana ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] break
i cant seem to break out of this loop. let me explain the variables you see: Enemy.ships = [] #an Enemy class variable that contains enemy ships self.missiles = [] an instance variable that appends how many Visible missiles my ship has fired Enemy.rects = [] an Enemy class variable that represents a rectangle for every ship in Enemy.ships Explosion() = a class where explosions occur QPoint() = is a pyqt function that takes a point x, y position as arguments im trying to destroy the ships if they hit a missile, even though i use pyqt this is mainly python code if Enemy.ships: for missile in self.missiles: for rect in Enemy.rects: if QPoint(missile.x + 5, missile.y) in rect: explosion = Explosion(rect.x(), rect.y()) self.explosions.append(explosion) break once the missile has hit 1 Enemy.rect i want to break and go to the next missile so the missile is destroyed and doesnt hit another Enemy, but for some reason the break i have isnt working and the same missile sometimes is hitting 2 different rects on the same iteration. i have done the same loop using a simple print statements on strings greater than a certain length and it breaks correctly. anyone have any ideas why the break isnt breaking out of the nested/inner loop but instead continuing to loop through the Enemies? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Break Help
On Tue, 29 May 2012 17:50:37 -0700 (PDT) PhantomsCore wrote: > > if gameIsDone: > if playAgain(): > missedLetters = '' > correctLetters = '' > gameIsDone = False > secretWord = getRandomWord(words) > else: > break > > That is my coding. When I try to run it I get "Break outside loop" > Because (surprise!) you are using break outside of a loop. Break is only valid to break out of a for or while loop, and no where else. What do you want to do with that program? Quit if playAgain() returns false? Just leave out the else entirely, and if gameIsDone is False, it will continue outside of that block. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Break Help
if gameIsDone: if playAgain(): missedLetters = '' correctLetters = '' gameIsDone = False secretWord = getRandomWord(words) else: break That is my coding. When I try to run it I get "Break outside loop" -- View this message in context: http://python.6.n6.nabble.com/Break-Help-tp4976225.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Break stament issue
Susana Iraiis Delgado Rodriguez wrote: Hello members!! Steven, I already changed the settings in the IDE to avoid the trouble when I type the code. In the other hand I added the pass statement so the script keep working even though it finds an error, but the scripts ignore the pass statement. Console prints: Traceback (most recent call last): File "", line 1, in File "mapnik_punto_sin_duda.py", line 44, in lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", line 282, in Shapefile return CreateDatasource(keywords) RuntimeError: wrong file code : -1997790976 This looks like an internal error of mapnik. I know nothing about mapnik, but my wild guess is that it expects a filename and you are giving it something else? Or the wrong filename? Or maybe it expects an open file, and you have given it a filename? -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Break stament issue
Hello members!! Steven, I already changed the settings in the IDE to avoid the trouble when I type the code. In the other hand I added the pass statement so the script keep working even though it finds an error, but the scripts ignore the pass statement. Console prints: Traceback (most recent call last): File "", line 1, in File "mapnik_punto_sin_duda.py", line 44, in lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", line 282, in Shapefile return CreateDatasource(keywords) RuntimeError: wrong file code : -1997790976 2011/6/14 James Reynolds > > > On Tue, Jun 14, 2011 at 2:59 PM, Susana Iraiis Delgado Rodriguez < > susana.delgad...@utzmg.edu.mx> wrote: > >> Hello members! >> >> I'm doing a script that needs to loop to get some information, in order to >> do that I'm using modules from OGR and Mapnik. These to get data from >> shapefiles, but some of the files have 0 elements, I wrote a line to >> validate it, but it hasn't worked, so I added a break to keep working. When >> I run the scipt I got the next error: >> Traceback (most recent call last): >> File "", line 1, in >> import mapnik_punto_sin_duda >> File "C:\Python26\mapnik_punto_sin_duda.py", line 23 >> break >>^ >> IndentationError: unexpected indent >> >> But I've read about this stamentet's use and I don't understand the reason >> I'm failing, the complete script is: >> import mapnik >> import os,fnmatch >> from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer >> from osgeo import ogr,gdal,osr >> >> #Registra todos los drivers de GDAL >> file_list = [] >> #Crear variable para buscar dentro de carpetas en el sistema >> folders = None >> #Se asigna el directorio raiz donde se van buscar los archivos, se hace un >> recorrido en la raiz >> for root, folders, files in os.walk( "c:\\" ): >> #Agregar a la lista los elementos que traiga os.path.join, los >> archivos que terminen en extension .shp >> for filename in fnmatch.filter(files, '*.shp'): >> file_list.append(os.path.join(root, filename)) >> #Recorrer la lista que se creo >> for row, filepath in enumerate(file_list, start=1): >> #Dividir la ruta en dos: directorio y nombre de archivo >> dir(LineSymbolizer().stroke) >> shapeData = ogr.Open(filepath) >> shp = 'Error al abrir el archivo' +filepath >> if shapeData is None: >> print shp >> break >> else: >> layer = shapeData.GetLayer() >> defn = layer.GetLayerDefn() >> geo = defn.GetGeomType() >> (ruta, filename) = os.path.split(filepath) >> archivo = os.path.splitext(filename) >> i = archivo[0]+'.png' >> >> m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") >> m.background = mapnik.Color('#EBEBEB') >> s = mapnik.Style() >> r=mapnik.Rule() >> >> if geo == 3: >> print "Trabajando mapa "+ruta+"\\"+filename+" con >> geometria "+ str(geo) >> >> r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) >> >> r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) >> s.rules.append(r) >> m.append_style('My Style',s) >> lyr = mapnik.Layer('world',"+proj=latlong >> +datum=WGS84") >> lyr.datasource = >> mapnik.Shapefile(base=ruta,file=archivo[0]) >> lyr.styles.append('My Style') >> m.layers.append(lyr) >> m.zoom_to_box(lyr.envelope()) >> mapnik.render_to_file(m,i, 'png') >> print "La imagen " +i+ " fue creada." >> elif geo == 2: >> print "Trabajando mapa "+ruta+"\\"+filename+" con >> geometria "+ str(geo) >> >> r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) >> s.rules.append(r) >> m.append_style('My Style',s) >> lyr = mapnik.Layer('world',"+proj=latlong >> +datum=WGS84") >> lyr.datasource = >> mapnik.Shapefile(base=ruta,file=archivo[0]) >> lyr.styles.append('My Style') >> m.layers.append(lyr) >> m.zoom_to_box(lyr.envelope()) >> mapnik.render_to_file(m,i, 'png') >> print "La imagen " +i+ " fue creada." >> elif geo == 1: >> print "Trabajando mapa "+ruta+"\\"+filename+" con >> geometria "+ str(geo) >> blue = >> mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) >> blue.allow_overlap = True >> s=mapn
Re: [Tutor] Break stament issue
Susana Iraiis Delgado Rodriguez wrote: Hello members! I'm doing a script that needs to loop to get some information, in order to do that I'm using modules from OGR and Mapnik. These to get data from shapefiles, but some of the files have 0 elements, I wrote a line to validate it, but it hasn't worked, so I added a break to keep working. When I run the scipt I got the next error: Traceback (most recent call last): File "", line 1, in import mapnik_punto_sin_duda File "C:\Python26\mapnik_punto_sin_duda.py", line 23 break ^ IndentationError: unexpected indent This error has nothing to do with break. Look at the error message, and the position of the ^ mark: the error occurs *before* the break statement, in the indentation. I can duplicate the error in Python 2.6 with this: >>> for t in (1, 2, 3): ... print t # four spaces ... break # one tab File "", line 3 break # one tab ^ IndentationError: unexpected indent Newer versions of Python give more helpful error messages: Python 3 reports "TabError: inconsistent use of tabs and spaces in indentation". You can fix this by using the tabnanny script supplied with Python. From the shell (not Python's interactive interpreter!) or the DOS prompt, run: python -m tabnanny -v replacing with the actual filename, and see what it says. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Break stament issue
On Tue, Jun 14, 2011 at 2:59 PM, Susana Iraiis Delgado Rodriguez < susana.delgad...@utzmg.edu.mx> wrote: > Hello members! > > I'm doing a script that needs to loop to get some information, in order to > do that I'm using modules from OGR and Mapnik. These to get data from > shapefiles, but some of the files have 0 elements, I wrote a line to > validate it, but it hasn't worked, so I added a break to keep working. When > I run the scipt I got the next error: > Traceback (most recent call last): > File "", line 1, in > import mapnik_punto_sin_duda > File "C:\Python26\mapnik_punto_sin_duda.py", line 23 > break >^ > IndentationError: unexpected indent > > But I've read about this stamentet's use and I don't understand the reason > I'm failing, the complete script is: > import mapnik > import os,fnmatch > from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer > from osgeo import ogr,gdal,osr > > #Registra todos los drivers de GDAL > file_list = [] > #Crear variable para buscar dentro de carpetas en el sistema > folders = None > #Se asigna el directorio raiz donde se van buscar los archivos, se hace un > recorrido en la raiz > for root, folders, files in os.walk( "c:\\" ): > #Agregar a la lista los elementos que traiga os.path.join, los > archivos que terminen en extension .shp > for filename in fnmatch.filter(files, '*.shp'): > file_list.append(os.path.join(root, filename)) > #Recorrer la lista que se creo > for row, filepath in enumerate(file_list, start=1): > #Dividir la ruta en dos: directorio y nombre de archivo > dir(LineSymbolizer().stroke) > shapeData = ogr.Open(filepath) > shp = 'Error al abrir el archivo' +filepath > if shapeData is None: > print shp > break > else: > layer = shapeData.GetLayer() > defn = layer.GetLayerDefn() > geo = defn.GetGeomType() > (ruta, filename) = os.path.split(filepath) > archivo = os.path.splitext(filename) > i = archivo[0]+'.png' > > m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") > m.background = mapnik.Color('#EBEBEB') > s = mapnik.Style() > r=mapnik.Rule() > > if geo == 3: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > > r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > elif geo == 2: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > elif geo == 1: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > blue = > mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) > blue.allow_overlap = True > s=mapnik.Style() > r=mapnik.Rule() > r.symbols.append(blue) > s.rules.append(r) > #s.rules.append(blue) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > else: >
[Tutor] Break stament issue
Hello members! I'm doing a script that needs to loop to get some information, in order to do that I'm using modules from OGR and Mapnik. These to get data from shapefiles, but some of the files have 0 elements, I wrote a line to validate it, but it hasn't worked, so I added a break to keep working. When I run the scipt I got the next error: Traceback (most recent call last): File "", line 1, in import mapnik_punto_sin_duda File "C:\Python26\mapnik_punto_sin_duda.py", line 23 break ^ IndentationError: unexpected indent But I've read about this stamentet's use and I don't understand the reason I'm failing, the complete script is: import mapnik import os,fnmatch from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer from osgeo import ogr,gdal,osr #Registra todos los drivers de GDAL file_list = [] #Crear variable para buscar dentro de carpetas en el sistema folders = None #Se asigna el directorio raiz donde se van buscar los archivos, se hace un recorrido en la raiz for root, folders, files in os.walk( "c:\\" ): #Agregar a la lista los elementos que traiga os.path.join, los archivos que terminen en extension .shp for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename)) #Recorrer la lista que se creo for row, filepath in enumerate(file_list, start=1): #Dividir la ruta en dos: directorio y nombre de archivo dir(LineSymbolizer().stroke) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp break else: layer = shapeData.GetLayer() defn = layer.GetLayerDefn() geo = defn.GetGeomType() (ruta, filename) = os.path.split(filepath) archivo = os.path.splitext(filename) i = archivo[0]+'.png' m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") m.background = mapnik.Color('#EBEBEB') s = mapnik.Style() r=mapnik.Rule() if geo == 3: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 2: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 1: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) blue = mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) blue.allow_overlap = True s=mapnik.Style() r=mapnik.Rule() r.symbols.append(blue) s.rules.append(r) #s.rules.append(blue) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." else: print "Algo fallo y no entro a ninguna de las geometrias" print "Listo" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor