How to take 3 inputs separated by a space in python, equivalent to scanf("%d%d%d",&a,&b,&n); in C.
Ruggero Turra
17.8k21 gold badges94 silver badges148 bronze badges
3 Answers 3
a, b, n = map(int, input('enter three values: ').split())
Example
enter three values: 3 5 6
>>> a
3
>>> b
5
>>> n
6
This solution is for Python 3.x In Python 2.x replace input with raw_input.
answered Mar 16, 2015 at 14:26
Cory Kramer
119k19 gold badges177 silver badges233 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Mar 16, 2015 at 14:26
Vivek Sable
10.3k6 gold badges45 silver badges63 bronze badges
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)
answered Mar 16, 2015 at 20:48
Ruggero Turra
17.8k21 gold badges94 silver badges148 bronze badges
Comments
lang-py