Menu ▾ ▴

input

Brian Kim
2008-05-26
2013-03-15
  • Brian Kim

    Brian Kim - 2008-05-26

    Hi, again, I am very new to PyDev, I started yesterday.
    I have a Python book, but I cannot find in it how to ask for input. For instance, in java, you can import kb.Scanner and do something like this:

    System.out.print("Enter your input: ");
    int inpt = kb.nextInt();

    And then inpt becomes what you entered. Can somebody tell me how to do this in Python?

    Thank you!

     
    • Hannes Mueller

      Hannes Mueller - 2008-05-26

      I recommend http://diveintopython.org/

      For reading the user input, try reading from sys.stdin - see the above book for an example

      hope that helps.

       
      • Brian Kim

        Brian Kim - 2008-05-26

        Thank you, now I can input things!

        One more question though. It seems like using sys.stdin reads the input as a string. is it possible to change it so that it reads integers, lists, dictionaries, etc?

         
        • Hannes Mueller

          Hannes Mueller - 2008-05-27

          No, it only reads Strings.
          You can, however, use casts like int() to automatically transform the input.
          if you have a properly formatted List or Dictionary (properly as in "like the print statement prints it"), you can use
          eval(THING_TO_TRANSFORM), {"__builtins__":[]}, {}) (the second parameters are there fore security purposes, to disable the builtin commands in this evaluation statement).

           
        • Fabio Zadrozny

          Fabio Zadrozny - 2008-05-27

          Actually, there's a function called 'input()' which will get the text entered and make an eval on the string entered and may return ints, lists, etc. See http://en.wikibooks.org/wiki/Python_Programming/Input_and_output for a reference.

          Cheers,

          Fabio

           
    • Hannes Mueller

      Hannes Mueller - 2008-05-27

      Sorry, that should have read eval(THING_TO_TRANSFORM, {"__builtins__":[]}, {}) - there was a surplus bracket