input( ) function in Python.
input( ) function in Python.
In this post we are going to learn about Input methods in Python. Let's start..!
In Python we have a print( ) function to print anything on console or screen. Like this we have so many inbuilt functions in Python. Now we will learn about a input( ) function in Python.
The function input( ) is used to take input from console ( screen ) in Python. This function can take input any input. It means numbers, alphabets and symbols.
Syntax : input( )
In this input( ) function you can write a text that helps user to give correct input. for ex input( "Enter number only :: " ) . Here user can understand that only number he have to give as input.
Here all data comes from user is by default in string ( str ) or character datatype.
[ If you don't know about datatypes first learn about datatypes, read my post on Datatypes in Python. Or simply Click here. This will open a post on Datatypes in Python. ]
Let's take input from user. Here we will take a name of user using input( ) function. Simply write input( ). You can write text inside for user understanding.
Now we will try to take two numbers from user and we will show sum of them to user. For this define two variables to store number. Simply write
num1 = input(" Enter first number :: ") same for second also
num2 = input(" Enter second number :: ")
[ If you don't know about variables and how to define variables check my post on Variables in Python. Or simply Click here. This will open a post on Variables in Python. ]
Now print addition of that two numbers on console ( screen ).
Ohhh..! Something goes wrong.!
We want output as 100 but we got 9010. What's wrong here ?
Let's solve this problem. We have learn before some time that a default datatype of input( ) function is string ( str ) or character . It means all data that comes from input( ) function will be of string datatype ( str ) or character datatype. That's why we got concatinated string in a output.
Now How to overcome this problem ?
The datatype of input( ) function is string ( str ) by default. Can we change that ? Can we set other datatype there ? and The answer is Yes..!! We can specify the datatype and take data of specified datatype only.
for ex. We want two integer numbers to add them. simply write
num1 = int( input( "Enter first number :: " ) )
num2 = int( input( "Enter second number :: " ) )
And now print addition of them
And we got what we want..!
Now you can specify different datatypes there and take data in type that we want.
Now take three numbers or four numbers and add them or subtract or do anything that you want. Try different ways and types.
This is all about input( ) function in Python.
If you have any doubts in this post then please ask me in comment section below. I will try to solve it.
If you like these post and you have learned something from this then share this post with your friends and family.
Keep learning always.....!!! 😇😇😇