tags:

views:

310

answers:

3

In C++, I can have take input like this:

cin >> a >> b >> c;

And a can be int, b can be float, and c can be whatever... How do I do the same in python?

input() and raw_input(), the way I'm using them, don't seem to be giving me the desired results.

+4  A: 

You generally shouldn't use input() in production code. If you want an int and then a float, try this:

>>> line = raw_input().split()
>>> a = int(line[0])
>>> b = float(line[1])
>>> c = " ".join(line[2:])

It all depends on what exactly you're trying to accomplish, but remember that readability counts. Obscure one-liners may seem cool but in the face of maintainability, try to choose something sensible :)

(P.S.: Don't forget to check for errors with try: ... except (ValueError, IndexError):)

A: 

Depending upon what you are doing, something like the getopt module could be useful, but only in certain situations and I'm not sure if it would apply in yours.

Paul Wicks
+2  A: 

Since the C++ cin reads from sys.stdin, you'll often do something more like the following.

import sys
tokens= sys.stdin.read().split()
try:
   a= int(token[0])
   b= float(token[1])
except ValueError, e:
   print e # handle the invalid input
S.Lott