Wednesday, July 3, 2024
HomeLanguagesPythonHow to input multiple values from user in one line in Python?

How to input multiple values from user in one line in Python?

For instance, in C we can do something like this: 

C




// Reads two values in one line
scanf("%d %d", &x, &y)


One solution is to use raw_input() two times. 

Python3




x, y = input(),  input()


Another solution is to use split() 

Python3




x, y = input().split()


Note that we don’t have to explicitly specify split(‘ ‘) because split() uses any whitespace characters as a delimiter as default. One thing to note in the above Python code is, both x and y would be of string. We can convert them to int using another line

x, y = [int(x), int(y)]

# We can also use  list comprehension
x, y = [int(x) for x in [x, y]]

Below is complete one line code to read two integer variables from standard input using split and list comprehension 

Python3




# Reads two numbers from input and typecasts them to int using
# list comprehension
x, y = [int(x) for x in input().split()] 


Python3




# Reads two numbers from input and typecasts them to int using
# map function
x, y = map(int, input().split())


Instead of using the input function to read a line of input from the user and then processing the line to extract the values, you can use the sys.stdin.readline function to read a line of input and then use the split method and a list comprehension to extract and convert the values to the desired type.

Python3




import sys
 
# Read a line of input
# Split the line into a list of values
# Extract and convert the values to integers using a list comprehension
 
line = [int(x) for x in sys.stdin.readline().split() ]


This article is contributed by Abhishek Shukla. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments