Given two integral numbers in string format, we have to define a function that can receive these numbers, convert into integers and return the sum as integer in Python.
给定两个整数格式的整数,我们必须定义一个函数,该函数可以接收这些数字,将其转换为整数,然后在Python中以整数形式返回总和。
Example:
例:
Input:
num1 = "10"
num2 = "20"
Function calling:
calculateSum(num1, num2)
Output:
Sum = 30
Logic:
逻辑:
Input two numbers in string format (We are just assigning the hard-coded values here), note that, numbers should be integral type.
以字符串格式输入两个数字(这里我们只是分配硬编码的值),请注意,数字应为整数类型。
Define a function, pass these values as parameters.
定义一个函数,将这些值作为参数传递。
Explicitly convert the values to integer by using int(variable/value).
通过使用int(variable / value)将值显式转换为整数。
Calculate the sum and return it.
计算总和并返回。
Program:
程序:
# function to calculate and return the sum
# parameters:
# a, b - integral numbers in string format
# return: sum of the numbers in integer format
def calculateSum (a,b):
s = int(a) + int(b)
return s
# Main code
# take two integral numbers as strings
num1 = "10"
num2 = "20"
# calculate sum
sum = calculateSum (num1, num2)
# print sum
print "Sum = ", sum
Output
输出量
Sum = 30