So far we have seen how to output/print a result and display it on the screen. Often you'll want to take input from a user and assign it to a variable . We can do the same using the input() function in Python. It has a very basic syntax :
- a = input()
Note that if the data type of the input variable is not specified , then the default data type is a string . If you want to take an integer, for instance , as input then simply assign the int type to the variable in the following way :
- a = int(input())
Let us take an example to understand this clearly.
a = input() print(a) b = int(input()) print(3*b).
Sometimes it is required to take space-separated objects as input , to do the same in Python , we will be using the lists and the split() method ( Do remember that by default the split method would remove the spaces in a string). This can be done in the following way :
- my_variable = list(input().split())
a = list(input().split()) print(a)
1 2 3 4
['1' , '2' , '3' ,'4']
Note that in the above method , the objects in the list will be stored in form of a string . In order to store the objects with a specific data type , we will need to use the map() function . We will be discussing this function in much more detail in the later sections of the tutorial , but for now the syntax for taking input() becomes :
- my_variable = list(map(int,input().split()))
Let us see this method in action in the example given below.
a = list(map(int,input().split())) print(a) print(type(a))
1 2 3 4
[1, 2, 3, 4] <class 'int'>