Example stylesheets for syntax highlight of code snippets.
[docutils/kirr.git] / sandbox / code-block-directive / tools / pygments-enhanced-front-ends / for-else-test.py.txt
blobd9687ecd5f0b7feee245dcebb876bfb15ed88918
1 Example for syntax highlight with Pygments
2 ==========================================
4 Translate this document to HTML with a pygments enhanced frontend::
6   rst2html-pygments --stylesheet=pygments-default.css
7    
8 or to LaTeX with::
9      
10   rst2latex-pygments --stylesheet=pygments-default.sty
11   
12 to gain syntax highlight in the output.
14 Convert between text <-> code source formats with::
16   pylit --code-block-marker='.. code-block:: python'
18 Run the doctests with::
20  pylit --doctest for-else-test.py
23 for-else-test
24 -------------
26 Test the flow in a `for` loop with `else` statement.
28 First define a simple `for` loop.
30 .. code-block:: python
32    def loop1(iterable):
33        """simple for loop with `else` statement"""
34        for i in iterable:
35            print i
36        else:
37            print "iterable empty"
38        print "Ende"
39   
40 Now test it:
41   
42 The first test runs as I expect: iterator empty -> else clause applies:
43       
44 .. code-block:: pycon
46    >>> execfile('for-else-test.py')
47    >>> loop1(range(0))
48    iterable empty
49    Ende
50   
51 However, the else clause even runs if the iterator is not empty in the first
52 place but after it is "spent":
54 .. code-block:: pycon
56    >>> loop1(range(3))
57    0
58    1
59    2
60    iterable empty
61    Ende
62    
63 It seems like the else clause can only be prevented, if we break out of
64 the loop. Let's try
66 .. code-block:: python
68    def loop2(iterable):
69        """for loop with `break` and `else` statement"""
70        for i in iterable:
71            print i
72            break
73        else:
74            print "iterable empty"
75        print "Ende"
76   
77 And indeed, the else clause is skipped after breaking out of the loop:
79 .. code-block:: pycon
81    >>> loop2(range(3))
82    0
83    Ende
84    
85 The empty iterator runs as expected:
87 .. code-block:: pycon
88       
89    >>> loop2(range(0))
90    iterable empty
91    Ende
92