Some basic questions

lucio lucio at movilogic.com
Wed Mar 26 16:01:19 EST 2003


Hi,

Brian Christopher Robinson wrote:

>I just began writing Python today and have a few basic questions:
>
>How can I read a single character from the standard input without consuming 
>any more input?
>  
>
sys.stdin.read(1)?
http://www.python.org/doc/current/lib/bltin-file-objects.html
http://www.python.org/doc/current/lib/module-sys.html

or maybe, if you want it unbuffered:
http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.074.htp

>Is there any way to write a boolean function?  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.
>

Actually, None evaluates to false. So you can just do:
if is_alpha("c"):
    print "of coz"

but you could change the return line to something like:
    return not not letters.match(c)
or
    return not (letters.match(c) == None)

So you have a [1|0] return value.

You could also use the ternary operator if we had one :)

See:
http://www.python.org/doc/current/lib/truth.html
http://www.python.org/doc/current/ref/customization.html (see __nonzero__)

>
>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.
>

Use a coma (,) after the print.

print "Hello, ",
print "World"
Hello, World.
http://www.python.org/doc/current/ref/print.html

Lucio.







More information about the Python-list mailing list