Input in Python

Python allows to take input from end user which can be stored in variable. To take input from user, see following example.

## Input function
name = input("Enter your name")

age = input("Enter age")
address = input("Enter your address")
profession = input("Enter profession")

print("My name is " + name + 
" my age is " + age + 
" I live in " +  address + " and i am " +  job )

Python provides input function to capture the input. This function performs three jobs:

  • It prints the string on screen “Enter your name” which is provided by programmer.
  • It waits for the input from keyboard.
  • It assigns input value to the variable( in this example name, age, address)

In this example program is asking for 3 inputs, name, address and profession. When input is entered, print function displays complete string on the screen. 


Input type from keyboard 

As you have seen that you can provide input from keyboard and this input can be stored in variable. By default the stored value is string type. In previous example variable name and variable age are string variables. Execute the following command and you will be amazed that both variable belongs to string class.

print(type(name))
print(type(age))

For better understanding see following example. 

tom_money = input("Enter Tom money: ")

bob_money = input("Enter Bob money: ")

print("Tom has " + tom_money +" dollars and Bob has " + bob_money + " dollars")

print("and total amount is ", tom_money + bob_money)

Execute this code and provide input to this example: Let’s say you have entered 6 for Tom and 5 for Bob and total amount should be 11 dollars but if you check the output, the answer is 65. Reason is both tom_money and bob_money variables are string type, instead of addition both string variables are concatenated.

Enter Tom money: 6
Enter Bob money: 5
Tom has 6 dollar and Bob has 5 dollar
and total amount is  65

But don’t worry there are other solutions to solve this problem, you can type cast these values into integers. 

tom_money = input("Enter Tom money: ")

bob_money = input("Enter Bob money: ")

t_m = int(tom_money)

b_m = int(bob_money)

print("Tom has " + tom_money +" dollars and Bob has " + bob_money + " dollars")

print("and total amount is ", t_m + b_m)

and the output is as expected

Enter Tom money: 6
Enter Bob money: 5
Tom has 6 dollars and Bob has 5 dollars
and total amount is  11

you can typecast these values right after the input is provided.

tom_money = int(input("Enter Tom money: "))

bob_money = int(input("Enter Bob money: "))

print("Tom has ", tom_money," dollars and Bob has", bob_money,"dollars")

print("and total amount is ", tom_money + bob_money)

## Check the output
Enter Tom money: 5
Enter Bob money: 6
Tom has  5  dollars and Bob has 6 dollars
and total amount is  11