[Tutor] reading stdin?
Jörg Wölke
lumbricus@gmx.net
Sat, 17 Feb 2001 17:20:07 +0100 (MET)
> On Fri, Feb 16, 2001 at 01:17:32PM -0500, Mr 804 wrote:
> |
> | how do I read stdin?
> |
>
> >>> data = raw_input( "Please give me some data: " )
> Please give me some data: Hello World
> >>> type( data )
> <type 'string'>
> >>> print data
> Hello World
> >>>
>
>
> raw_input is good if you want random stuff or text stuff,
> if you want other stuff, input can be helpful
>
> >>> data = input( "Enter some data: " )
> Enter some data: 2
> >>> type( data )
> <type 'int'>
> >>> print data
> 2
> >>>
>
>
> However, be careful how you use input() :
>
> >>> data = input( "Enter some data: " )
> Enter some data: foo
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<string>", line 0, in ?
> NameError: There is no variable named 'foo'
> >>>
>
> >>> i = 2
> >>> data = input( "Enter some data: " )
> Enter some data: lambda x : x + i
> >>> type( data )
> <type 'function'>
> >>> print data
> <function <lambda> at 007A8574>
> >>> print data( 3 )
> 5
> >>>
>
>
> input won't always do what you want, if the user inputs bad stuff.
> You can use raw_input, then convert the string how you want to. Ex:
>
> >>> try :
> ... data = int( raw_input( "Enter a number: " ) )
> ... except ValueError , err :
> ... print "You didn't enter a valid number"
> ...
excuse me if that's a silly question:
why not just
try:
data = input("Enter number: ")
except:
"wrong"
which would trap all errors?
greets jö!
>
>
> If you have more questions, just ask.
>
> HTH,
> -D
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Sent through GMX FreeMail - http://www.gmx.net