# An innocent question...

There is a very funny thread currently in the PyAr (Python Argentina) mailing list.

It all started when "Galileo Galilei" asked about how to do a very simple thing. He presented this code:

```age = int(raw_input('How old are you?'))
if age<18:
print 'You are underage'
else:
print 'You are a grownup'
```

Ok, the original was... not quite as polite, but the code is the same. So far, nothing strange. But then he asked this:

How can I make it so that if the user enters something that is not a number, it does something like this:

```print 'I have no supercow powers'
```

or maybe

```print 'Typing error'
```

You can probably imagine that asking this kind of thing should produce maybe two answers. Right?

That is indeed the case, and you can see that in the answer by Facundo Batista or Ezequiel.

Except... what if we wanted it to keep asking in case the user entered not-a-number?

Then, my friends... it's about taste, and it's all Juan Pedro Fisanotti's fault.

Here's my take:

```while True:
break
print 'No ingresaste un numero!'
```

Yes, I admit, a bit old fashioned. And there was a cry of "no, break sucks, it's not right", which leads to this by Manuel Aráoz

```age = raw_input('Your age?')
while not age.isdigit():
print "That's not a number!"
```

Which caused cries of "Having raw_input twice is ugly!", which leads to (again by Manuel Aráoz):

```get_age = lambda: raw_input('Your age?')
age = get_age()
while not age.isdigit():
print 'Not a number!'
age = get_age()
```

Here Patricio Molina digs up PEP 315.

And then Alejandro Santos says something like "This is easier in C, because we can assign a value to age in the while's condition". Please remember this.

Now Pablo Zilliani gives his version, which is, I must say, perfect in some ways:

```age = reset = msg = 'Age?: '
while not age.isdigit():
age = raw_input(msg)
msg = "%r is not a number!, %s" % (age, reset)

print age
```

Here Gabriel Genellina decides to defend break by hitting everyone in the head using Knuth which should have a much stronger effect than Hitler.

And now, we start veering into weird waters. Here is what news proposes, which I must say, I admire... from a respectful distance.

First, the relevant code:

```edad = "0" # Entra igual la primera vez

edad = raw_input ("¿Cuantos años tenes? ")
print "No ingresaste un nro!"
```

But what, exactly, is firstTrue?

```import inspect

def firstTrue(cond):
""" devuelve True siempre la primera vez que se la ejecuta,
las veces subsiguientes evalua la condicion """
stack = inspect.stack()[1] # El stack del programa llamador
line = stack[2] # Nro de linea desde la que llame a firstTrue
del stack

if not "line" in firstTrue.__dict__:
# Primera vez que llamo a la funcion
firstTrue.line = line
return True
elif firstTrue.line != line:
# Llame a la funcion desde otro punto del programa
firstTrue.line = line
return True

return cond
```

Then, I bring up generators, which leads to Claudio Freire's, which almost works, too:

```age = ''
def invalidAge():
yield True
while not age.isdigit():
print "Not a number"
yield True
yield False

for i in invalidAge():

print age
```

And then Fabian Gallina is the second one to bring up C's assignments inside conditions.

You know, I can't accept that. I will not accept C being easier for this.

So, with a little help from the python cookbook...

```age=[1]

while not age |asig| raw_input('Age? '):
print 'Not a number!'

print u'You are %s years old'%age[0]
```

```class Infix:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
return self.function(other)
def __rlshift__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __rshift__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)

def opasigna (x,y):
x[0]=y
return y.isdigit()

asig=Infix(opasigna)
```

And then, Pablo posts this gem:

```import inspect

def assign(var, value):
stack = inspect.stack()[1][0]
stack.f_locals [var] = value
del stack
return value

while not assign("age", raw_input('Age? ')).isdigit():
print u'Not a number!'

print u'You are %s years old' % age
```

Which is, IMVHO, about as far from trivial as you can get here. Of course the thread is not dead yet ;-)

# Preparing a rst2pdf release for next week

Since this is the first post that appears in Planet Python, a small intro is in order.

Hi, my name is Roberto Alsina, I am a former KDE developer, amateur programmer [1] , python fan.

This post (and many you will see from me) is about rst2pdf, a tool to convert restructured text to PDF. For example, it turns the python library reference into this PDF (not production quality yet).

If you are a rst2pdf 0.11 user, or a sphinx or docutils user who wants to try an alternative way to create PDFs, then I would like your help testing the SVN trunk code.

These are some of the new features since 0.11:

• PDFBuilder, a Sphinx extension to generate PDFs.
• Kerning (requires wordaxe from SVN)
• AAFigure support (diagrams using ASCII Art)
• PageBreaks can be odd/even/any
• Support for advanced page counters (manual numbering, roman/arabic/letters)
• Much better styling, specially for tables.

So, please, take a look, you may like it!

 [1] That just means I love programming.

# Yet more Python Spreadsheet Goodness!

The guy at Mission: Cognition actually released his spreadsheet!

I havenot tested it, but it looks sweet.

See it here

# Yay! sphinx-rst2pdf-builder works!

Ok, it kinda works a little.

I got commit rights in the mercurial repo, so now you can get the very very alpha version here.

This triggered several bugs in rst2pdf, so you need SVN rst2pdf for it to work.

What works:

• Glossary
• Plain restructured text ... with some caveats (example: footnotes are semi-broken)
• Index generation (not 100%, but maybe 75%)

I don't know what other pieces of sphinx require specific rst2pdf support, but I will be hitting them as they come.

## 2009-07-01 17:58

Some guys at PyAr are translating the python tutorial to spanish.

That tutorial, like all the new python docs, uses sphinx.

Since sphinx is very popular, I want rst2pdf to work as well as possible as Sphinx's PDF producer. So, two different things itching, I started scratching.

Well, progress has been made. While the sphinx changes currently reside only on my computer, I will publish them soon, and the rst2pdf changes are already committed.

Here's a sample to whet your appetite.

# AAFigure in rst2pdf

As of today, rst2pdf supports Chris Liechti's awesome aafigure.

What does it mean? It means you can put this in your document:

```+-------+       +-------+
|   A   |------>|   B   |
+-------+       +-------+
```

And get this (and as a PDF drawing, not as an image, so you can copy the text from it):

So it's an awesome way to add simple diagrams to your restructured text documents that look good in plain text, on the web, and on PDF.

Aafigure can create lots of interesting drawings, check their docs for examples here

It currently requires aafigure from bzr (0.3 won't work).

# Rst2pdf 0.11 released!

Rst2pdf is a tool to generate PDF files directly from restructured text sources via reportlab.

This version includes many bugfixes and some new features compared to the previous 0.10.1 version, including but not limited to embedding PDF images, much improved image sizing, nicer list layouts, better styling, page backgrounds, and more than 15 bugs fixed. A full changelog is included at the bottom of this message.

Rst2pdf aims to support the full restructured text feature set, and is very close to that goal, while also including some of the more experimental features, like a source code directive with syntax highlighting and math notation support with LaTeX-like syntax.

It supports embedding arbitrary fonts, both True Type and PS Type 1, both raster and vector images (including SVG), page transition effects, multiple, flexible page layouts, cascading styles, and much, much more.

Here are the changes in this version compared to 0.10.1:

• Degrade more gracefully when one or more wordaxe hyphenators are broken (currently DWC is the broken one)
• Fixed issue 132: in some cases, with user-defined fontAlias, bold and italic would get confused (getting italic instead of bold in inline markup, for instance).
• New stylesheet no-compact-lists to make lists... less compact
• SVG images now handle % as a width unit correctly.
• Implemented issue 127: support images in PDF format. Right now they are rasterized, so it's not ideal. Perhaps something better will come up later.
• Fixed issue 129: make it work around a prblem with KeepTogether in RL 2.1 it probably makes the output look worse in some cases when using that. RL 2.1 is not really supported, so added a warning.
• Fixed issue 130: use os.pathsep instead of ":" since ":" in windows is used in disk names (and we still pay for DOS idiocy, in 2009)
• Fixed issue 128: headings level 3+ all looked the same
• Ugly bugfix for Issue 126: crashes when using images in header + TOC
• New tstyles section in the stylesheet provides more configurable list layouts and more powerful table styling.
• Better syntax highlighting (supports bold/italic)
• Workaround for issue 103 so you can use borderPadding as a list (but it will look wrong if you are using wordaxe <= 0.3.2)
• Added fieldvalue style for field lists
• Added optionlist tstyle, for option lists
• Added collection of utility stylesheets and documented it
• Improved command line parsing and stylesheet loading (guess extension like latest rst2latex does)
• Fixed Issue 67: completely new list layouting code
• Fixed Issue 116: crashes caused by huge images
• Better support for %width in images, n2ow it's % of the container frame's width, not of the text area.
• Fixed bug in SVG scaling
• Better handling of missing images
• Added missing styles abstract, contents, dedication to the default stylesheet
• Tables style support spaceBefore and spaceAfter
• New topic-title style for topic titles (obvious ;-)
• Vertical alignment for inline images (:align: parameter)
• Issue 118: Support for :scale: in images and handle resizing of inline images
• Issue 119: Fix placement of headers and footers
• New background property for page templates (nice for presentations, for example)
• Default to px for image width specifications instead of pt
• Support all required measurement units ("em" "ex" "px" "in" "cm" "mm" "pt" "pc" "%" "")
• New automated scripts to check test cases for "visual differences"
• Respect images DPI property a bit like rst2latex does.
• Issue 110: New --inline-footnotes option
• Tested with reportlab from SVN trunk
• Support for Dinu Gherman's svglib. If both svglib and uniconvertor are available, svglib is preferred (for SVG, of course). Patch originally by rute.
• Issue 109: Separate styles for each kind of admonition
• For Issue 109: missing styles are not a fatal error
• Issue 117: TOCs with more than 6 levels now supported (raised limit to 9, which is silly deep)

# rst2pdf progress report

Since the last release, there have been many changes, improvements and fixes in rst2pdf.

At the bottom of this post you will find (maybe incomplete) list, but I wanted to share a couple of relatively large advances.

Presentations

I have wanted to make rst2pdf useful for presentations for quite a while. And now it's getting close.

I am writing a small tutorial about it, but you can see a demo already.

The changes that make this possible are:

• Fixed bugs regarding page layout
• Added support for page backgrounds (including SVG!)

This was in large part because of César Rodas, who wanted something simple and text-based to do his ZendCon presentation, so he asked me about it, and I was ashamed to give him a broken tool.

See how that works? I am driven by embarrassment. That's embarrasing.

Major stylesheet improvements

The related changes are way too many (see below), but it also happened for a reason: I wanted to make prettier documents.

So, since most people seems to like Sphinx's style, I wanted to look similar.

Did I achieve it? Yes and no, take a look:

But it's just a draft, I didn't look at fonts, or weight of the headings, or even at what pygments color scheme sphinx is using.

But anyway, even this rough stylesheet made me find a dozen bugs or problems in rst2pdf.

So, the main lesson here is, please tell me what you can and can't do with rst2pdf, because there are whole areas I am not even looking at, day-to-day.

The final thing is... the next release is going to be awesome. But then again, I always say that, don't I?

Changes as of today:

• Workaround for issue 103 so you can use borderPadding as a list (but it will look wrong if you are using wordaxe <= 0.3.2)
• Added fieldvalue style for field lists
• Added optionlist tstyle, for option lists
• Added collection of utility stylesheets and documented it
• Improved command line parsing and stylesheet loading (guess extension like latest rst2latex does)
• Fixed Issue 67: completely new list layouting code
• Fixed Issue 116: crashes caused by huge images
• Better support for %width in images, n2ow it's % of the container frame's width, not of the text area.
• Fixed bug in SVG scaling
• Better handling of missing images
• Added missing styles abstract, contents, dedication to the default stylesheet
• Tables style support spaceBefore and spaceAfter
• New topic-title style for topic titles (obvious ;-)
• Vertical alignment for inline images (:align: parameter)
• Issue 118: Support for :scale: in images and handle resizing of inline images
• Issue 119: Fix placement of headers and footers
• New background property for page templates (nice for presentations, for example)
• Default to px for image width specifications instead of pt
• Support all required measurement units ("em" "ex" "px" "in" "cm" "mm" "pt" "pc" "%" "")
• New automated scripts to check test cases for "visual differences"
• Respect images DPI property a bit like rst2latex does.
• Issue 110: New --inline-footnotes option
• Tested with reportlab from SVN trunk
• Support for Dinu Gherman's svglib. If both svglib and uniconvertor are available, svglib is preferred (for SVG, of course). Patch originally by rute.
• Issue 109: Separate styles for each kind of admonition
• For Issue 109: missing styles are not a fatal error
• Issue 117: TOCs with more than 6 levels now supported (raised limit to 9, which is silly deep)

## 2009-05-17 13:51

So, rst2pdf 0.10 was not ok. The setup.py that worked on 0.9 simply didn't work for the new version.

Good thing is, Christoph actually undestands setuptools, so he could fix it and deliver a neat 0.10.1 for your PDF-generating pleasure.

Post 0.10.1, I have already fixed one bug, Issue 117.

# Released rst2pdf 0.10!

If you don't know what I'm talking about, rst2pdf lets you create PDF files from a simple, very lightly marked pure text format called restructured text and is the easiest way to create nice documentation for your free software project and more!

Here is the manual which is created using rst2pdf itself from this.

And here's a (maybe partial) list of the changes, which should convince you that you really want this version:

• Issue 87: Table headers can be repeated in each page (thanks to Yasushi Masuda)
• Issue 93: Line number support for code blocks (:linenos: true)
• Issue 107: Support localized directives/roles (example: sommaire instead of contents)
• Issue 112: Fixed crash when processing empty list items
• Issue 98: Nobreak support, and set as default for inline-literals so they don't hyphenate.
• Slightly better tests
• Background colors in text styles work with reportlab 2.3
• Issue 99: Fixed hyphenation in headers/footers (requires wordaxe 0.3.2)
• Issue 106: Crash on demo.txt fixed (requires wordxe 0.3.2)
• Issue 102: Implemented styles for bulleted and numbered lists
• Issue 38: Default headers/footers via options, config file or stylesheet
• Issue 88: Implemented much better book-style TOCs
• Issue 100: Fixed bug with headers/footers and Reportlab 2.3
• Issue 95: Fixed bug with indented tables
• Issue 89: Implemented --version
• Issue 84: Fixed bug with relative include paths
• Issue 85: Fixed bug with table cell styles
• Issue 83: Fixed bug with numeric colors in backColor attribute
• Issue 44: Support for stdin and stdout
• Issue 79: Added --stylesheet-path option
• Issue 80: Send warnings to stderr, not stdout
• Issue 66: Implemented "smart quotes"
• Issue 77: Work around missing matplotlib
• Proper translation of labels (such as "Author", "Version" etc.) using the docutils languages package. (r473)
• Fixed problems with wrong or non-existing fonts. (r484)
• Page transition effect support for presentations (r423)