如何确定哪个变量更接近21?

时间:2019-02-24 00:05:22

标签: python

我是尝试创建游戏21的初学者。我搜索了类似的信息,但是无法或错过与我的问题有关的信息。如果两个分数都高于或低于21,我希望能够确定哪个分数更接近21。例如,如果用户在被问到是否要再次滚动时得分为'n',并且分数为18他和13计算机,用户应该会赢。

1 个答案:

答案 0 :(得分:0)

You can use the abs(number) function to solve this:

num1 = int(input("Please enter the first number: "))
num2 = int(input("Please enter the second number: "))
key = lambda num: abs(21-num)
print("{} is closer than {} to 21".format(min(num1, num2, key=key), max(num1, num2, key=key)))