0

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
asked Mar 16, 2015 at 14:21
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.

answered Mar 16, 2015 at 14:26
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

answered Mar 16, 2015 at 14:26

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)
answered Mar 16, 2015 at 20:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.