Taking Multiple Inputs from Users in Python

A developer often wants a user to be able to put multiple inputs in a single line. In C/C++ this feat is achieved by scanf. In Python, we have two methods to take multiple inputs in a single line.

  • Split() method
  • List comprehension

Split() method:

It uses a specified separator to break the given input. It will take whitespace as separator if no separator is provided. split() function is generally used to split a Python string, but it can also help in taking multiple inputs.

Syntax:

input().split(separator, maxsplit)

Let’s take an example:

# Python program showing how to

# multiple input using split

# taking two inputs at a time

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

print(“Number of boys: “, x)

print(“Number of girls: “, y)

print()

# taking three inputs at a 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()

# taking two inputs at a time

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

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

print()

# taking multiple inputs at a time

# and type casting using list() function

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

print(“List of students: “, x)

Output:

 

List Comprehension:

It is used to define and create lists in Python. Lists like mathematical statements can be created just in one line. It is also used in obtaining multiple inputs from a user.

Leave a Reply

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