User Input In Python
Last updated
Last updated
input() function is used to get input from the user. It takes input from the user and then it converts it into a string.
A program has meaning only if it interacts with user, in simpler terms, it takes instruction from user and execute itself based on it. To understand better , let's make a simple addition program.
In [3]:
Now , no matter how many times you run this program output is always going to be 30. This program is not doing anything meaningful.
But what if user can give values of num1 and num2 , then this program has some value. Here comes user input. user input takes value from user and python operates on these values accordingly.
You can pass a 'string' under the brackets of input() functions as parameter , to let the user know what kind of information user need to give. For Example:
In [ ]:
Now passing a string in input() is completely optional , but it's a good practice as it tells user what values should he provide.
The default data-type of values inputted by user is String. Let's see:
In [ ]:
Hence , no matter what value user enters , the default data type of the value will be String.
Can you tell me the value of add in this program?
In [ ]:
It will give you output : 1020.
As we have seen in previous example, failure of addition program because user input values were in string , so we need to convert data type of user input values with the help of type conversion, Something like this:
In [ ]:
Note:You can convert user input values to any desired data type such as float,bool,str limiting the rules of Type casting that we have learned before.
Write a Program to calculate Simple interest with all the inputted user values.
Write a small calculator program with all the inputted user values.
Ask user's birthyear and calculate his age.