The Wayback Machine - https://web.archive.org/web/20240904162952/https://www.geeksforgeeks.org/taking-multiple-inputs-from-user-in-python/
Open In App

Taking multiple inputs from user in Python

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. 

Using split() method :

This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator. Generally, users use a split() method to split a Python string but one can use it in taking multiple inputs.

Syntax : 

input().split(separator, maxsplit)

Implementations: 

Python
# Python program showing how to
# multiple input using split

# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)

# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)

# taking two inputs at a time
a, b = input("Enter two values: ").split()
print("First number is {} and second number is {}".format(a, b))

# taking multiple inputs at a time 
# and type casting using list() function
x = list(map(int, input("Enter multiple values: ").split()))
print("List of students: ", x)

Output: 

Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15
Enter two values: 5 10
First number is 5 and second number is 10
Enter multiple values: 5 10 15 20 25
List of students: [5, 10, 15, 20, 25]

Using map() with split():

Using map() with the split() method in Python is a powerful way to efficiently process input values. The split() method allows breaking a string into substrings based on a specified delimiter, often useful for parsing user input. By combining it with map() and a desired transformation function (like int() for converting to integers), we can swiftly convert these substrings into the desired data types and assign them to variables for further processing or calculations.

Syntax:

variable1, variable2, ... = map(datatype, input().split())

Implementations:

Python
#Example with integers
a, b, c = map(int, input("Enter three integers separated by spaces: ").split())
print("Sum:", a + b + c)

#Example with floats:
x, y = map(float, input("Enter two floats separated by a space: ").split())
print("Product:", x * y)

#Example with strings:
name, age = input("Enter your name and age separated by a space: ").split()
print("Hello,", name + "! You are", age, "years old.")

Output:

Enter three integers separated by spaces: 5 10 15
Sum: 30
Enter two floats separated by a space: 3.5 2.5
Product: 8.75
Enter your name and age separated by a space: Alice 25
Hello, Alice! You are 25 years old.

Using List comprehension : 

List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements in one line only. It is also used in getting multiple inputs from a user. 

Example: 

Python
# Python program showing
# how to take multiple input
# using List comprehension

# taking two input at a time
x, y = [int(x) for x in input("Enter two values: ").split()]
print("First Number is: ", x)
print("Second Number is: ", y)

# taking three input at a time
x, y, z = [int(x) for x in input("Enter three values: ").split()]
print("First Number is: ", x)
print("Second Number is: ", y)
print("Third Number is: ", z)

# taking two inputs at a time
x, y = [int(x) for x in input("Enter two values: ").split()]
print("First number is {} and second number is {}".format(x, y))

# taking multiple inputs at a time 
x = [int(x) for x in input("Enter multiple values: ").split()]
print("Number of list is: ", x) 

Output :

Enter two values: 5 10
First Number is: 5
Second Number is: 10
Enter three values: 5 10 15
First Number is: 5
Second Number is: 10
Third Number is: 15
Enter two values: 5 10
First number is 5 and second number is 10
Enter multiple values: 5 10 15 20 25
Number of list is: [5, 10, 15, 20, 25]


Note: The above examples take input separated by spaces. In case we wish to take input separated by comma (, ), we can use the following: 

Python
# taking multiple inputs at a time separated by comma
x = [int(x) for x in input("Enter multiple value: ").split(",")]
print("Number of list is: ", x) 

Output

Screenshot-from-2023-12-15-13-31-28

Please see https://ide.geeksforgeeks.org/BHf0Cxr4mx for a sample run.

Taking multiple inputs from user in Python – FAQs

How to Take Multiple Inputs in Python?

Taking multiple inputs in Python can be done in various ways, depending on how the input is provided and how you want to process it.

How to Use input() Function for Multiple Inputs?

You can use the input() function to take multiple inputs from the user in a single line and then process them accordingly.

How to Split User Input in Python?

You can split the user input using the split() method. This is especially useful when the user inputs multiple values separated by spaces.

Example:

# Taking multiple inputs in a single line
inputs = input("Enter multiple values separated by space: ").split()

# Printing the inputs
print(inputs)

If the user enters: 10 20 30 40, the output will be:

['10', '20', '30', '40']

What is the Use of map() Function with input()?

The map() function is used to apply a specific function to all items in an input list. This is useful for converting all input strings to integers or floats, for example.

Example:

# Taking multiple numeric inputs in a single line and converting them to integers
inputs = list(map(int, input("Enter multiple integers separated by space: ").split()))

# Printing the integer inputs
print(inputs)

If the user enters: 10 20 30 40, the output will be:

[10, 20, 30, 40]

How to Take Multiple Numeric Inputs in Python?

Combining input(), split(), and map() functions is an efficient way to take multiple numeric inputs.

Example:

# Taking multiple numeric inputs in a single line
numbers = list(map(float, input("Enter multiple numbers separated by space: ").split()))

# Printing the numeric inputs
print(numbers)

If the user enters: 1.5 2.5 3.5, the output will be:

[1.5, 2.5, 3.5]


Previous Article
Next Article

Similar Reads

Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstrate a dictionary # with multiple inputs in a key. i
4 min read
Python - Distance between collections of inputs
scipy.stats.cdist(array, axis=0) function calculates the distance between each pair of the two collections of inputs. Parameters : array: Input array or object having the elements to calculate the distance between each pair of the two collections of inputs. axis: Axis along which to be computed. By default axis = 0 Returns : distance between each p
1 min read
Find the average of an unknown number of inputs in Python
Prerequisites: *args and **kwargs in Python The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyword, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the wo
3 min read
Python Arcade - Handling Mouse Inputs
In this article, we will learn how we can handle mouse inputs in the arcade module in Python. In Arcade, you can easily handle the mouse inputs using these functions: on_mouse_motion(): Syntax: on_mouse_motion(x, y, dx, dy) Parameters: x : x coordinatey : y coordinatedx : change in x coordinatedy : change in y coordinate on_mouse_press(): Syntax :
3 min read
Compute the square root of complex inputs with scimath in Python
In this article, we will cover how to compute the square root of complex inputs with scimath in Python using NumPy. ExampleInput: [-1 -2] Output: [0.+1.j 0.+1.41421356j] Explanation: Square root of complex input.NumPy.emath.sqrt method The np.emath.sqrt() method from the NumPy library calculates the square root of complex inputs. A complex value is
3 min read
Python: OpenCV findHomography Inputs
OpenCV, the popular open-source computer vision and machine learning library, offers a wide range of tools for image processing and computer vision tasks. One of the critical functions in the context of image alignment and perspective transformation is findHomography. This function is used to find the transformation matrix that maps points from one
4 min read
Taking input from console in Python
What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks like this. Here we write a command and to execute
2 min read
Python VLC MediaPlayer – Taking Screenshot
In this article we will see how we can take screen shot of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. A screenshot, als
2 min read
Taking Screenshots using pyscreenshot in Python
Python offers multiple libraries to ease our work. Here we will learn how to take a screenshot using Python. Python provides a module called pyscreenshot for this task. It is only a pure Python wrapper, a thin layer over existing backends. Performance and interactivity are not important for this library. Installation Install the package pyscreensho
2 min read
Taking input in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ( prompt ) raw_input ( prompt ) input (): This funct
5 min read
Creating multiple user types and using proxy models in Python Django
In this article, we will understand the concept of the proxy model and the implementation of multiple user types depending on the requirements of your application in Django. What is the Proxy model in Django? An inherited proxy model can have a few extra functionalities, methods, and different behaviors than the parent model as defined by the creat
9 min read
How to input multiple values from user in one line in Python?
For instance, in C we can do something like this: C/C++ Code // Reads two values in one line scanf("%d %d", &x, &y) One solution is to use raw_input() two times. C/C++ Code x, y = input(), input() Another solution is to use split() C/C++ Code x, y = input().split() Note that we don't have to explicitly specify spli
2 min read
How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
User-defined Exceptions in Python with Examples
Prerequisite: This article is an extension to Exception Handling. In this article, we will try to cover How to Define Custom Exceptions in Python with Examples. Example: class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python Python throws errors and
4 min read
Fetch top 10 starred repositories of user on GitHub | Python
Prerequisites: Basic understanding of python, urllib2 and BeautifulSoup We often write python scripts to make our task easier, so here is the script which helps you to fetch top 10 starred repositories of any user on GitHub.You just need Github username (For example: msdeep14) to run the script.Script Explanation: First access the repository url of
4 min read
Python | User groups with Custom permissions in Django
Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the different packages available on tour booking servi
4 min read
Get a list as input from user in Python
We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to get input a list from the user using Python. Example: Input : n = 4, ele = 1 2 3 4Output : [1, 2, 3, 4]Input : n = 6, ele = 3 4 1 7 9 6Output : [3, 4, 1, 7, 9, 6]Get a list as input from user in Python using Loop C/C++ Cod
2 min read
Python | Fetch your gmail emails from a particular user
If you are ever curious to know how we can fetch Gmail e-mails using Python then this article is for you.As we know Python is a multi-utility language which can be used to do a wide range of tasks. Fetching Gmail emails though is a tedious task but with Python, many things can be done if you are well versed with its usage. Gmail provides IMAP acces
5 min read
Add a User in Linux using Python Script
Creating a user via command line in Linux is a tedious task. Every time someone joins your organization and you need to type a long Linux command rather than doing this you can create a python script that can ask for you the username and password and create that user for you. Examples: Input : Enter Username : John Password: **** Output : User succ
1 min read
Deleting a User in Linux using Python Script
Deleting a user from your system or server via a python script is a very easy task. You just need to pass the username of the user and the script will remove the details and all the files of that user.This python script uses userdel Linux command to delete the user.You can directly use userdel command if you remember the command but if you don't th
2 min read
User Defined Data Structures in Python
In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures: Non-primitive data types: Python has list, set, and dictionary as its non-prim
4 min read
Send message to Telegram user using Python
Have you ever wondered how people do automation on Telegram? You may know that Telegram has a big user base and so it is one of the preferred social media to read people. What good thing about Telegram is that it provides a bunch of API's methods, unlike Whatsapp which restricts such things. So in this post, we will be sharing how to send messages
3 min read
Python Tweepy - Getting the screen name of a user
In this article we will see how we can get the screen name of a user. Screen name is the username of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their screen name, often in a shortened version. All the screen names must be unique. Ident
2 min read
Python - User object in Tweepy
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user.
6 min read
Python Tweepy - Getting the ID of a user
In this article we will see how we can get the ID of a user. ID is the unique identification marker of the twitter account. ID is given to the user by Twitter, the user can not select or change their own ID. In order to get the ID we have to do the following : Identify the user screen name of the profile. Get the User object of the profile using th
2 min read
Python Tweepy - Getting the location of a user
In this article we will see how we can get the location of a user. The location of the user account need not be the exact physical location of the user. As the user is free to change their location, the location of the account can even by a hypothetical place. The location attribute is optional and is Nullable. Identifying the location in the GUI :
2 min read
Python Tweepy - Getting the name of a user
In this article we will see how we can get the name of a user. Name is the display name of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their display name. Unlike screen names, the names need not be unique. Moreover the names can be in a
2 min read
Python Tweepy – Getting the description of a user
In this article we will see how we can get the description of a user. The description of the describes a user account. The description attribute is optional and is Nullable. Identifying the description in the GUI : In the above mentioned profile the description is : Your one-stop destination to attain Coding Nirvana... In order to get the descripti
2 min read
Python Tweepy – Getting the URL of a user
In this article we will see how we can get the URL of a user. The url attribute is a URL provided by the user in association with their profile. The URL attribute is optional and is Nullable. Identifying the URL in the GUI : In the above mentioned profile the url is : geeksforgeeks.org In order to get the URL we have to do the following : Identify
2 min read
Python Tweepy – Getting the number of followers of a user
In this article we will see how we can get the number of followers of a user. The followers_count attribute provides us with an integer donating the number of followers the user account has. Identifying the number of followers in the GUI : In the above mentioned profile the number of followers are : 17.8K (17, 800+) In order to get the number of fo
2 min read
Article Tags :
Practice Tags :