我正在尝试定义一个函数,它接受 2 个参数,将它们相加,如果两个参数的总和以 5 结尾,它报告 2。如果它不以 5 结尾,则返回 8。
有什么想法吗?
我想做一个 if 语句,但我很困惑如何检查一个数字是否以 5 结尾(或者是 5)。
感谢您的帮助,尝试自学如何编程是如此困难却又如此有益:)
请您参考如下方法:
解决方案
我的回答假设您正在检查整数(从您的问题来看这似乎很合理):
def sum_ends_with_5(a, b):
"""
Checks if sum ends with "5" digit.
"""
result = a + b
return 2 if result % 10 == 5 else 8
或更灵活(有任意数量的参数):
def sum_ends_with_5(*args):
"""
Checks if sum ends with "5" digit.
"""
result = sum(args)
return 2 if result % 10 == 5 else 8
它是如何工作的(又名测试)
函数的行为如下:
>>> sum_ends_with_5(5)
2
>>> sum_ends_with_5(3)
8
>>> sum_ends_with_5(2, 8)
8
>>> sum_ends_with_5(7, 8)
2
>>> sum_ends_with_5(10, 20, 3, 2)
2
简化版
因此,如果您想以更短、更灵活的方式编写它,您可以这样做:
def sum_ends_with_5(*args):
return 2 if sum(args) % 10 == 5 else 8
