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..
In Python, the raw_input function gets characters off the console and concatenates them into a single str as its output. When just one variable is found on the left-hand-side of the assignment operator, the split function breaks this str into a list of str values .
One solution is to use raw_input() two times. Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as a delimiter as default.
To print multiple variables in Python, use the print() function. The print(*objects) is a built-in Python function that takes the *objects as multiple arguments to print each argument separated by a space.
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')
You can also read from sys.stdin
import sys
a,b = map(int,sys.stdin.readline().split())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With