How to take space separated input in Python?

Introduction:

In this article I am going to explain  how to take space separated input in Python?

 There may be a situation when we want to enter more than one values but all the  values should be separated by space and we hit the enter key after the last input.

 To fulfill this requirement we should know that how to take space separated input in Python.

 We are using several types of input devices for user input .  The standard input device is a keyboard.  In this article, I am going to discuss how to take space separated input in Python using a keyboard.

Program No. 1

x=input().split()

print(x)

After the execution of above code, user can supply space separated input as follows

10 20 30

Output

[’10’, ’20’, ’30’]

Explanation

I am using input() function to take input from keyboard. Input() function takes input as string data type that’s why all the inputs ‘10’ ‘20’ ‘30’ are of type string.

The split() function with zero argument splits the given string on the basis of space and returns a list of elements that’s why we are having the output [’10’, ’20’, ’30’].

How to take space separated input in Python

 Program No 2

This program is going to show that how to take space separated input in form of integers.

x=list(map(int,input().split()))

print(x)

After the execution of above code, user can supply space separated input as follows

10 20 30

Output

[10, 20, 30]

Explanation

I am using map function to apply int() function over user input .

 map() function is taking two arguments.

First argument is the name of function I want to apply on user input that is int() function.

Int() function is converting string data type into integer data type.

i am providing user input as second argument.

Finally, list function is converting the object returned by map function into a list.

How to take space separated input in Python

Conclusion

If you are taking input from keyboard be careful about the data type because by default the data type of keyboard

Leave a Reply

Your email address will not be published. Required fields are marked *