How do I enter multiple values ​​from the user on one line in Python?

Python Methods and Functions

// Reads two values ​​on one line

scanf ( "% d% d" , & amp; x, & amp; y) 

One solution is to use raw_input () twice.

x, y = raw_input (),  raw_input ()

Another solution is to use split ()

Note that we don't need to explicitly specify split (& # 39; & # 39;), because split () uses any whitespace characters as the delimiter by default.

In the above Python code, note that x and y would be strings. We can convert them to int using another string

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

Below is the complete one-line code to read two integer variables from stdin using splitting and

x, y = raw_input (). split ()

# Reads two numbers from input and casts them to int using
# list comprehension

x, y = [ int (x) for x in raw_input (). split ()] 

# Reads two numbers from input and outputs them to int using
# map function

x, y = map ( int , raw_input (). split ())

Note that in Python 3 we are using input () instead of raw_input ().

This article is provided by Abhishek Shukla . Please post comments if you find something wrong or if you would like to share more information on the topic under discussion





Tutorials