Followers

Saturday, December 14, 2019

Simple Input and Output | Python

Simple Input and Output 

Hello friends, Welcome to Blog. Today we will talk about Simple input and output in Python. 


In python, to get input from the user interactively, you can use Built-in-function input(). The function input() is used in the following manner :
variable_to_hold_the_value_ = Input(<prompt to be displayed>)
For Example, 
                name = input('what is your name')
The above statement will display the prompt as : 
        >>> name = input('what is your name')
        >>> what is your name 
And in front of which you can type your name. The value that you type in front of the displayed prompt will be assigned to given variable, name in above case. Now consider the following command sequence :
     name = input('Enter your name =')
>>> Enter your name = Saurav
     age = input('Enter your age =')
>>>Enter your age = 18 
>>>name
>>>'Saurav'
>>>age
>>>'18'
In the above code we used input() function to input two values name and Age. 
But input() has a property, which you must be aware of. The input() function always returns a value string type. Notice carefully in above code - while displaying both values Name and Age, Python Has Enclosed Both the values in quotes i.e., as 'Simar'
and '18'. This is because whatever value you enter through input() function is treated as a string. 
Now, what are its consequences, especially when you are entering a number? In order to understand this, Consider the following code:
>>>age = input('What is your age ?')
>>>What is your age? 18
>>>age+1
Traceback (most recent call last):
   File "<ipython-input-9-eac256a954eb>", line 1, in <module>

TypeErrormust be str, not int 


See, Python raised an error when you tried to add 1 to ae whose value you entered as 18. The reason is obvious and clear - Python cannot add on integer to a string. Since variable age received a value 18 through the input(), it actually had '18' in it i.e., string value '18'; thus you cannot add an integer to it. 
You can try this input() function by yourself just click the Online Compiler option in the menu bar or just CLICK HERE .
You can check yourselves the type of variable age whose value you entered through the input() function;

>>>age = input("What is your age ?")
>>>What is your age ? 18
>>>age
>>>'18'
>>>type(age)
>>>str

You can see above the type of variable age shows str. 

So with this, we end with this Post. This was a very small post as both of the topic was very small. And don't forget to follow me, that will give you notifications of my new updates.
JAI HIND!!! 
VANDE MATARAM!!!!!      

No comments:

Post a Comment

If you have any doubts, please do let me Know.