Section 2.2. Program Input and the raw_input()Built-in Function


2.2. Program Input and the raw_input()Built-in Function

The easiest way to obtain user input from the command line is with the raw_input() built-in function. It reads from standard input and assigns the string value to the variable you designate. You can use the int() built-in function to convert any numeric input string to an integer representation.

  >>> user = raw_input('Enter login name: ')   Enter login name: root   >>> print 'Your login is:', user   Your login is: root


The earlier example was strictly for text input. A numeric string input (with conversion to a real integer) example follows below:

  >>> num = raw_input('Now enter a number: ')   Now enter a number: 1024   >>> print 'Doubling your number: %d' % (int(num) * 2)   Doubling your number: 2048


The int() function converts the string num to an integer so that the mathematical operation can be performed. See Section 6.5.3 for more information in the raw_input() built-in function.

Core Note: Ask for help in the interactive interpreter

If you are learning Python and need help on a new function you are not familiar with, it is easy to get that help just by calling the help() built-in function and passing in the name of the function you want help with:

>>> help(raw_input) Help on built-in function raw_input in module __builtin__: raw_input(...)     raw_input([prompt]) -> string


Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.'


Core Style: Keep user interaction outside of functions

It's very tempting for beginners to put print statements and raw_input() functions wherever they need to display information to or get information from a user. However, we would like to suggest that functions should be kept "clean," meaning they should silently be used purely to take parameters and provide return values. Get all the values needed from the user, send them all to the function, retrieve the return value, and then display the results to the user. This will enable you to use the same function elsewhere without having to worry about customized output. The exception to this rule is if you create functions specifically to obtain input from the user or display output.More importantly, it is good practice to separate functions into two categories: those that do things (i.e., interact with the user or set variables) and those that calculate things (usually returning results). It is surely not bad practice to put a print statement in a function if that was its purpose.




Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net