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.
>>> 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"
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