Finding the sum of two numbers if both numbers are integer or float, is not a problem. But what will happen if the numbers are string variable? Like “10”, “20” etc ? In this python tutorial, we will learn how to find the sum of two numbers if both of them are in String. Let’s take a look :
Python program :
Python has one inbuilt method called int() to convert a string to an integer. So, just pass a string to this method and it will return you one integer value. But it will fail if the number is not actually a number. Means, it will work for “10”,”20″,”30″ etc. which are actually numbers, but not for a string like “hello”,”hi” etc. which are not string numbers. Let’s take a look at the following program (The source code is available here):
The commented numbers in the above program denote the step number below :
1. calculateSumFor() function is to calculate the sum of two numbers. These numbers should be in string format. It will return the sum of the numbers. You can see that we are converting the numbers from a string to a number using int() method.
2. Create two string variables to hold the numbers in string format: firstNumber and secondNumber.
3. Now, call the method calculateSumFor and print out the result.
If you run this code, it will look as below :
As you can see that the sum of the two numbers is printed on the screen. The calculation was done even though the values are a string.
If you have anything other than the number, it will throw one ValueError. Take a look at the example below :
It will through one error like below :
So, you should always use try-catch while doing this type of conversion.
It will print like below :
We have seen how to find the sum of two string numbers in python. This method is useful in many cases. e.g., if you have one server in python and you are getting numbers in string format from the client side. So, you can use this process to convert them. Try to run the examples above and let me know if you find any trouble.