[Tutor] setting variables off the command line

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Thu, 20 Jul 2000 10:20:32 -0700 (PDT)


On Thu, 20 Jul 2000, peter church wrote:

>             I know this is a very simple question to answer but I
> cannot find any example of how it is done in the python docs I have
> also looked in the O'Reilly book as well
> 
>     how do I collect variables from users from within a python program
> i.e
> 
>     print  what is  your name  ?
>     read (name)
>     print hello name !

There are a few ways to do this.  A simple way is to use the raw_input()
function, which will return the string the user enters, up to the newline.  
Your program above would look like:

  print "What is your name?"
  name = raw_input()
  print "Hello %s!" % name

The only thing with raw_input() is that it always returns the string
representation, so if you're doing things with numbers, you'll probably
need to do an int() or a float() on your result.


Another way to do input is with the input() function.  It'll read user
input, and evaluate it --- this takes care of having to worry about
coersing your value into a number, but makes inputting strings weirder:


###
>>> x = input()
5
>>> type(x)
<type 'int'>
>>> x
5
>>> s = input()
"hello world"
>>> s
'hello world'
>>> s = input()
hello world
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1
    hello world
             ^
SyntaxError: unexpected EOF while parsing
###


Notice how inputting a string requires quotes.  However, this does allow
the user to do stuff like

###
>>> import math
>>> x = input("Enter a math function: ")
math.sin(.3)
>>> x
0.295520206661
###


since it's evaluating what you type in at the input, just as if you had
entered it from the interpreter prompt.