Reading User Input
Taking input from user is a vital part of any application as it makes the application more interactive and user friendly. Further, a real world applications takes different actions based on user input.
Python provides a built-in function called input which is used for reading user entered values from the keyboard. This method takes a string as an argument which represents the message to be displayed to the user when asking him for entering some values. input method returns the value read from the keyboard always in string format. This means that if you are expecting anything other than string in your program, you need to convert it manually to that type.  Example,

name = input("Enter your name") # read user entered data
print("Hello !!" + name)        # use keyboard entered values further

Output will be as below. Text in green is the user entered data.

Enter your name
demouser
Hello !! demouser

Note that input method blocks program execution till the user enters some values and hits enter key. Till then the program keeps waiting for user input.

Type Conversion
Suppose you want to accept two numbers from user, add them and show their sum to the user. If you are familiar with input method, you would write the code as

first_number = input("Enter first number")   # read a value
second_number = input("Enter second number") # read another value
sum = first_number + second_number           # add values
print("Sum is " + sum)                       # display sum

When the above code is executed, it behaves as below

Enter first number
20
Enter second number
23
Sum is 2023

Notice the output, it should have been 43 but it is instead 2023 which was unexpected. What is the reason?
The reason for this output is that input method returns values in string format as mentioned earlier. Thus, while performing addition it was actually concatenating strings as ’20’ + ’23’ which results in ‘2023’.
Therefore, in order for your program to work correctly, you should convert the return value of input method as per your requirement. Return value of input can be converted to int, float using methods int and float respectively. Both these methods take a value as an argument and return the corresponding representation. Example,

int('54')    # will return 54
int(2.8)     # will return 2
float('5.4') # will return 5.4
float(3)     # will return 3.0

Remember that value to both these methods should be convertible to int or float or in other words, it should be a number. Trying to pass an invalid value will result in an error. Example,

print(int("two"))   # ValueError: invalid literal for int() with base 10: 'two'
print(float("2we")) # ValueError: could not convert string to float: '2we'

Now, the corrected version of the program to add two numbers will look like

first_number = input("Enter first number")   # read a value
first_number = int(first_number)             # convert string to int
second_number = input("Enter second number") # read another value
second_number = int(second_number)           # convert string to int
sum = first_number + second_number           # add values
print("Sum is " + sum)                       # display sum

It is also possible to read input and convert it in the same line as

first_number = int(input("Enter first number"))

Return value of input method is passed as argument to int method and its return value is assigned to a variable.  This is called method chaining where the output of one method becomes the input of another. Method chaining works from innermost method to outer methods.

Converting to string
Just like a string can be converted to an int or float, there is a method to do the opposite, that is, to convert an int or float to string using str method. This method takes a value as an argument and returns the same value converted to a string. Example of usage follows

value_string = str(2.3)     # convert a float to string
print(value_string)         # prints 2.3
print(type(value_string))   # prints <class 'str'>
value_string = str(23)      # convert an int to string
print(value_string)         # prints 23
print(type(value_string))   # prints <class 'str'>

 

0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.