input function

When the python program needs to get input from the user, we should use input function.




Syntax

variable = input('Prompt message')

Where,

variable - where we want to store the input

input() - Used to read the user input

Prompt message - will be printed on the screen while getting the input

Example

#input function example

name = input('Enter Your Name')

print(name)           

The input function reads the input and always converts it into a string.

So, we need to typecast the input based on our need.


Example

a = input('Enter first number')
b = input('Enter second number')

ans = a + b

#since the inputs are taken as a string, 
#it will not print the sum.
#It will print the concatenation of 2 inputs

print(ans) 

In the above program, if we give the first number as 10 and second number as 20 then the ans will not have the result 30.

Instead it will have the concatenation of 10 and 20 (as the inputs are taken as a string).

So, the ans will be 1020.




Typecasting string input into integer

Using int() function we can convert the string input to integer.


The below program will get two numbers from the user and print their sum.

Example

#Below inputs are explicitly converted into integer
#using int() function

a = int(input('Enter first number'))
b = int(input('Enter second number'))

ans = a + b

print(ans)

int() function converts any datatype to integer.

float() function converts any datatype to float.