Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
George John

To read multiple variables in language C, we write something like −

//Read three variable in one line
scanf(“%d %d %d”, &x, &y, &z)

Currently python does not have an equivalent to scanf(). However, python provides regular expressions which are more powerful and verbose than scanf() format strings. In Python, to provide multiple values from user, we can use −

input() method: where the user can enter multiple values in one line, like −

>>> x, y, z = input(), input(), input()
40
30
10
>>> x
'40'
>>> y
'30'
>>> z
'10'

From above output, you can see, we are able to give values to three variables in one line.

To avoid using multiple input() methods(depends on how many values we are passing), we can use the list comprehension or map() function.

Passing multiple values using list comprehension

>>> x,y,z = [int(x) for x in input().split()]
9 12 15
>>> x
9
>>> y
12
>>> z
15

In above line of code, i have typecast the input values to integers. In case you don’t want that & your inputs are of mixed type, you can simply type −

>>> x,y,z = [x for x in input().split()]
40 10 "hello"

Using map function

Another way to pass multiple values from user is to use map function.

>>> x,y,z = map(int, input().split())
40 54 90
>>> x
40
>>> y
54
>>> z
90

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.