+

Taking multiple inputs from a user in Python

A developer often wants the user to enter multiple values ​​or inputs on a single line. In C ++ / C, a user can get multiple inputs on one line using scanf , but in Python, a user can get multiple values ​​or inputs on one line in two ways.

  • Using the split()
  • Using the comprehension list

Using the split () :
This function helps to get multiple inputs from the user. It breaks the given input with the specified delimiter. If no delimiter is specified, then any white space is a delimiter. Typically the user will use the split () method to split a Python string, but it can be used to type multiple times.

Syntax :

 input (). split (separator, maxsplit) 

Example:

# Python program showing as
# multiple inputs using separation

 
# accepting two inputs at the same time

x, y = input ( "Enter a two value:" ). split ()

print ( "Number of boys:" , x)  

print ( "Number of girls:" , y)

print ()

 
# accepting three inputs at the same time

x, y, z = input ( "Enter a three value:" ). split ()

print ( "Total number of students:" , x)

print ( "Number of boys is: " , y)

print ( " Number of girls is: " , z)

print ()

 
# accepting two logins at the same time

a, b = input ( "Enter a two value:" ). split ()

print ( "First number is {} and second number is {}" . format (a, b))

print ()

  
# accept multiple inputs at the same time
# and typecast with the list () function

x = list ( map ( int , input ( "Enter a multiple value:" ). split ()))

print ( "List of students:" , x)

Output:

Usage comprehension list :
List comprehension — it is an elegant way to define and create a list in Python. We can create lists like mathematical expressions in just one line. It is also used to get multiple inputs from the user.

Example :

# Display Python program
# how to take multiple inputs
# using comprehension list

 
# accepting two inputs at the same time

x, y = [ int (x) for x in input ( "Enter two value:" ). split ()]

print ( "First Number is:" , x)

print ( "Second Number is:" , y)

print ()

  
# accepting three inputs at the same time

x, y, z = [ int (x) for x in input ( "Enter three value:" ). split ()]

print ( "First Number is:" , x)

print ( "Second Number is:" , y)

print ( "Third Number is:" , z)

print ()

 
# accepting two logins at the same time

x, y = [ int (x) for x in input ( " Enter two value: " ). split ()]

print ( "First number is {} and second number is {}" . format (x, y))

print ()

 
# accept multiple inputs at the same time

x = [ int (x) for x in input ( "Enter multiple value:" ). split ()]

print ( "Number of list is:" , x) 

Output:

Get Solution for free from DataCamp guru