- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
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.