tags:

views:

254

answers:

2

I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?

I'm looking for the equivalent of:

scanf("%d%d", &i, &j); // accepts "10 20\n"

One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way?

This is not for live use. Just for learning.

+7  A: 

No, the usual way is raw_input().split()

In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings

Don't use input() for that. Consider what happens if the user enters

import os;os.system('do something bad')

gnibbler
Note that starting with Python 3.0, `raw_input` was renamed to `input`. (And to get the original behavior of `input`, use `eval(input)`.)
Stephan202
...that should be "apply `eval` to the output of `input`".
Stephan202
Yes, the obvious behaviour in 3 is much better, but I wish they had dropped some warnings into 2.6 about those changes. I guess I need to study the upgrade guide
gnibbler
no it should be `int(input()`, if you do `eval(input())` in python3 you get a very dangerous backdoor because the user will be able to execute any python statement (even os.system) with your user's rights.
dalloliogm
@dialloliogn: read again. I made a *general* remark about how to get Python 2's `input` behavior in Python 3.
Stephan202
+1  A: 

You can also read from sys.stdin

import sys

a,b = map(int,sys.stdin.readline().split())
MAK