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 Data Science using 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:

Taking multiple inputs in Data Science using Python - PST Analytics

List Comprehension:

It is there to define and create lists in data science using python. Lists like mathematical statements can be created just in one line. It is also there in obtaining multiple inputs from a user.

Taking multiple inputs in Data Science using Python - PST Analytics

To learn more, you can check out this and this.

Leave a Reply

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