Python | 编写函数以字符串格式查找两个整数的和

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


翻译自: https://www.includehelp.com/python/write-a-function-to-find-sum-of-two-integral-numbers-in-string-format.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值