How to take user defined input in Python?

Being a beginner you might have a doubt to how to take user defined input in python.

In Python, we use the ‘ input() ‘  function to take the input from the user. As Python is simple language the input and output functions are named according to their working.

Syntax:

variable_name=input()

For Example:

n=input()

Input:

hello

Output:

hello

By default, Python considers any input as string when we use input statement.

For Example:

p=input()
q=input()
r=input()
print(p,q,r)
print(type(p))
print(type(q))
print(type(q))

Input:

2345
77.6
Raju

Output:

2345 77.6 Raju
<class 'str'>
<class 'str'>
<class 'str'>

Here we took three inputs p,q,r using the input function from the user . The output function in python is ‘ print() ‘ which is according to its function. If we print them we got the same values which are entered by the user, and the function type gives the type of that variable. We got the output as ” <class ‘str’> “, it says that the variable is of type string. So here p,q,r are of the type string.But according to the user p,q,r={2345,77.6,”Raju”} and data types are { ‘integer’ ,’float’,’string’ }.

How to take user-defined input in Python according to the datatype?

By just mentioning the datatype before using the input function is enough to have the input of the desired type.

For Example:

p=int(input())
q=float(input())
r=str(input())
print(p,q,r)
print(type(p))
print(type(q))
print(type(r))

Input:

2345
77.6
Raju

Output:

2345 77.6 Raju
<class 'int'>
<class 'float'>
<class 'str'>

The input is taken as { ‘integer’ ,’float’,’string’ } as mentioned by user.
While taking the input for ‘r‘ even if we give the data type like string or not it is considered as a string as shown above.

Taking input by giving appropriate message to the user

By just writing the message inside the input statement using double quotes gives the appropriate message to the user while giving the input.

For Example:

p=int(input('enter an integer')) 
q=float(input('enter a floating point value')) 
r=str(input('enter a string')) 
print(p,q,r) 
print(type(p)) 
print(type(q)) 
print(type(r))

Here using single or double quotes doesn’t matter since Python considers everything as string either in single quotes(”) or double quotes(“”).

Input:

enter an integer 2345                                                                                                                  
enter a floating point value 77.6                                                                                                    
enter a string Raju

Output:

2345 77.6 Raju 
<class 'int'> 
<class 'float'> 
<class 'str'>

So, to make the user clear we can give appropriate messages as shown above.

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *