Some basic questions

Martin v. Löwis martin at v.loewis.de
Wed Mar 26 16:20:09 EST 2003


Brian Christopher Robinson <a at b.c> writes:

> How can I read a single character from the standard input without consuming 
> any more input?

On Windows, you can use msvcrt.getch. On Unix, this is somewhat more
tricky, as you have to put the terminal into raw mode.

> Is there any way to write a boolean function?  

Sure. In Python < 2.2, return 0/1; in Python >= 2.2, return
True/False.

> I wanted to write a simple 
> is_alpha function (which may be in the standard library but I'm leanring), 
> and this is what I came up with:
> 
> def is_alpha(c) :
>     letters = re.compile("[a-zA-Z]")
>     return letters.match(c)
> 
> Instead of checking for true or false I check to see if None is returned, 
> but that seems a little kludgy.

Notice that the result of this function can be used in an if statement
as-if it were a boolean: None counts as logical false, and a match
object counts as logical true. It is indeed Pythonic to rely on these
relations.

If you want to return true/false, it is best to write

      return letters.match(c) != None

> How can I print to standard out without printing a newline?  It seems that 
> the print statement always adds a newline and I haven't found any other 
> outputting functions yet.

Add a comma after the last object

  print 1,2,3,

This prints a space, so that the next print will continue on the
same line, with proper spacing.

If you don't want that, you need to use sys.stdout.write.

HTH,
Martin




More information about the Python-list mailing list