How to take 3 inputs separated by a space in python, equivalent to scanf("%d%d%d",&a,&b,&n); in C.
3 Answers
Use raw_input() to get values from keyboard.
- Ask User to enter values from the keyboard by
raw_input() - Split user enters values by space.
- Use type casting to convert string to integer.
Demo:
>>> a = raw_input("Enter three number separated by space:")
Enter three number separated by space:1 3 2
>>> print a
1 3 2
>>> print type(a)
<type 'str'>
>>> a1 = a.split()
>>> a1
['1', '3', '2']
>>> int(a1[0])
1
>>>
Exception Handling:
Best practise to handle exception during Type Casting because User might enter alpha values also.
Demo:
>>> try:
... a = int(raw_input("Enter digit:"))
... except ValueError:
... print "Enter only digit."
... a = 0
...
Enter digit:e
Enter only digit.
Note:
Use input() for Python 3.x and raw_input() for Python 2.x
Comments
As written in the documentation you can use regular expression to parse the string as in scanf.
input_string = raw_input()
import re
m = re.search("([-+]?\d+) ([-+]?\d+) ([-+]?\d+)", input_string)
if m is None:
raise ValueError("input not valid %s" % input_string)
input_numbers = map(int, input_string_splitted)