Register Login

How to take Input() in Python?

In python there are two inbuilt functions to take input from keyboard which are:

Python takes input from the keyboard and store the input in a variable to perform such operations.

1) raw_input() Function

This function works with the python 2.x and older version, it takes the input in the exact same manner as entered by the user and converts it to string then store them in the variable.

Example

# Python program to explain raw_input() function

# Prompt user to enter value
myname = raw_input('What is your Name: ')

# Print entered a value on the screen
print('My name: ', myname)

# Print variable type
print(type(myname))

# Prompt user to enter value
age = raw_input('What is your Age: ')

# Print entered a value on the screen
print('My Age: ', age)

# Print variable type
print(type(myname))

Output

What is your Name: ss
My name:  ss
<class 'str'>
What is your Age: 66
My Age:  66
<class 'int'>

2) input() Function

Input() function prompt user to enter the value, it takes value from the user and convert them in string and save in variable for further use, Which means when you enter an integer value it will convert into a string. In this case we need to use typecasting in our code to explicitly convert it into an integer.

Example

# Python program to explain input() function

# Prompt user to enter value
myname = input('What is your Name: ')

# Print entered value on screen
print('My name: ', myname)

# Print variable type 
print(type(myname))

# Prompt user to enter value
age = input('What is your Age: ')

# Print entered value on screen
print('My Age: ', age)

# Print variable type 
print(type(myname))

Output

What is your Name: ss
My name:  ss
<class 'str'>
What is your Age: 66
My Age:  66
<class 'str'>

Explanation

In the above code, we took input from the user using the input() function available in python 3.x versions. After taking the input from the user we printed the type of the variable using the type() function. The type() function returns the type of value stored in the variable. In python, every input we give is stored as a string. This is why even after providing an integer value to ‘age’ the value stored is a string.

To change a string to integer do:

Example

# Prompt user to enter value
age = int(input('What is your Age: '))
# Print variable type
print(type(age))

Output

What is your Age: 32

<class 'int'>

Explanation

In the above code, we converted the input string value into an integer. Using a built-in function int(). Thus, now the value stored in variable ‘age’ is of type ‘int’.

Conclusion

The raw_input() and input() are two built-in function available in python for taking input from the user. The raw_input() function works with python 2.x version. The input() function works with python 3.x version. The value stored in the variable when taking the input from the user will be of type string.


×