0

How to take 3 inputs separated by a space in python, equivalent to scanf("%d%d%d",&a,&b,&n); in C.

0

3 Answers 3

2
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.

Sign up to request clarification or add additional context in comments.

Comments

2

Use raw_input() to get values from keyboard.

  1. Ask User to enter values from the keyboard by raw_input()
  2. Split user enters values by space.
  3. 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

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.