Python tutorial to calculate the sum of two string numbers

Introduction :

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 :

#1
def calculateSumFor(first,second):
	return int(first) + int(second)

#2
firstNumber = "100"
secondNumber = "200"

#3
print(calculateSumFor(firstNumber,secondNumber))

Explanation :

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 :
python sum of two string numbersAs 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 :

def calculateSumFor(first,second):
	return int(first) + int(second)

firstNumber = "hello"
secondNumber = "200"

print(calculateSumFor(firstNumber,secondNumber))

It will through one error like below :
python sum of two string numbersSo, you should always use try-catch while doing these type of conversion.

def calculateSumFor(first,second):
	try:
		return int(first) + int(second)
	except ValueError:
		return -1

firstNumber = "hello"
secondNumber = "200"

sum = calculateSumFor(firstNumber,secondNumber)

if sum == -1:
	print("Conversion failed.")
else:
	print(sum)

It will print like below :
python sum of two string numbers

Conclusion :

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.

Leave a Reply