How to Accept User Input With Python

Rather than receiving input from a file, you can create Python programs that take direct user input from a command line. To do this, you can use either the "input" function or the "raw_input" function. These functions differ in how they process incoming data. The "input" line will attempt to process user input, such as converting numbers to integers or floating point decimals. The "raw_input" function will simply take all input as a string of characters. You can process input later, but you'll learn that in differing cases, one of these functions might be better suited for your needs than the other.

Things You'll Need

  • Python Interpreter
Show More

Instructions

    • 1

      Take user input with the "raw_input" function. This will prompt the user to enter an input value:

      >>>x = raw_input()
      42
      >>>

    • 2

      Take user input using the "input" function. This will prompt the user to input data the same way as the "raw_input" function:

      >>>y = input()
      42
      >>>

    • 3

      Check both variables. The value taken by the "raw_input" function represents a string. This is because the raw_input function does not try to match input with a data type. The input function processes the input, and changes it to an integer:

      >>>type(x)
      <type 'str'>
      >>>type(y)
      <type 'int>

    • 4

      Get indirect user input from files. While it is not a direct form of user input, information from files can be used to get user information stored from previous user sessions. Open files using the "open" function, and read information using the "readline" function:

      >>>z = open('/home/user.txt', 'r')
      >>>input_line = z.readline()
      >>>input_line
      'This is a line from the file'

Related Searches:

References

Comments

Related Ads

Featured