User Input In Python

What is input() function?

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]:

num1 = 10
num2 = 20
add = num1+num2
print(add)
30

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.

Parameter to be passed in input() function:

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 [ ]:

company = input("Please Enter the Company name:")

Now passing a string in input() is completely optional , but it's a good practice as it tells user what values should he provide.

Data Type of Values inputted by user:

The default data-type of values inputted by user is String. Let's see:

In [ ]:

age = input("please enter your age:")

print(type(age))
<class 'str'>

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 [ ]:

num1 = input("please enter first number: ")
num2 = input("please enter second number: ")
add = num1+num2

It will give you output : 1020.

Converting Data type of user input values:

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 [ ]:

num1 = int(input("please enter first number: "))
num2 = int(input("please enter second number: "))
add = num1+num2

print(add)
30

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.

Assignment:

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

Last updated