Followers

Sunday, February 23, 2020

Reading Numbers - Simple Input and Output

Hello friends, Welcome to our website. Today we will talk about Reading Numbers in Python. 

To understand this New topic you need to First read our last post which was on :

Reading Numbers  

String values cannot be used for arithmetic or other numeric operations. For these operations, you need to have values of Numeric type (integer or Float ). 
But what would you do if you have to read numbers (int or float)? 
The function input( ) returns the entered value in string type only. Then what is the way out?
Don't worry, Python offers two functions int( ) and float( ) to be used with input( ) to convert the values received through input( ) into int and float types. You can :
  • Read in the value  using input( ) function.
  • And then use int( ) or float( ) function with the read value to change the type of input value to int or float respectively.
For Example:-
>>>age = input("what is your age ?")
what is your age? 16 
>>>age = int(age)
>>>age + 1
>>>17 

You can also combine these two steps in a single step too, i.e., as :
<variable name> =int(input(<prompt string>))
OR
<variable name> =float(input(<prompt string>))
After using int( ) and float( )functions with input( ), You can check yourselves using type( ) functons that the type of read value is now int or float now. For Example:- 
>>> marks = float(input("enter marks :"))
enter marks : 73.5
>>>type(marks)
>>>float

Possible Errors When Reading Numeric Values

If you are planning to input an integer or floating-point number using input( ) inside bint( ) or float( ) such as shown below :
age = int(input("enter your age :"))
OR
percentage = float(input("enter your percentage : "))
Then you must ensure that the value you are entering must be ina form that is easily convertible to the target type. 
In other words :
  • while inputting integer values using int( ) with input( ), make sure that the value being entered must be int type compatible. 
  • While inputting floating-point values using float( ) with input( ), make sure that the value being must be float type compatible. 
Please note that values like 73, 73. and  .73 are all float convertible, hence Python will be able to convert them to float and no error shall be reported if you enter such values.
 
So with this, we end with this Topic, don't forget to follow me so that you can get the latest updates of my new posts that I upload weekly, I will try my best to upload daily OR you can Sign up for Newsletters at the top of the Blog and that will give you E-mail updates of my New Post.
Jai Hind!!!!
Vande Mataram!!!

No comments:

Post a Comment

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