我有两个变量,value1和value2。我想通过if语句查看这些值中哪个更接近数字21。在伪代码中,
If value1 is closer to 21:
Event1
elif value2 is closer to 21:
Event2
else:
Event3
您可以使用绝对值函数来查看21和值之间哪个差更大:
value1 = 40
value2 = 8
if abs(21 - value1) < abs(21 - value2):
print('value1 is closer')
else:
print('value2 is closer')
输出:
value2 is closer
想想你通常会怎么做。您将找到两个值之间的正差异,并查看哪个更小!
def foo(number,val1,val2):
if abs(number-val1) < abs(number-val2):
event1()
elif abs(number-val1)>abs(number-val2):
event2()
else:
event3()
我做这个例子是为了检查哪个数字更接近:
#Setting variables
val1 = 2
val2 = 1
cond = 21
check1 = val1
check2 = val2
#arrays to save numbers between
arr1 = []
arr2 = []
#Conditioning values
#Value 1 check
if(check1 > cond):
while check1 > cond:
# print(check1)
arr1.append(check1)
check1 -= 1
elif(check1 == cond):
arr1 = [cond]
else:
while check1 < cond:
# print(check1)
arr1.append(check1)
check1 += 1
#Value 2 check
if(check2 > cond):
while check2 > cond:
# print(check2)
arr2.append(check2)
check2 -= 1
elif(check2 == cond):
arr2 = [cond]
else:
while check2 < cond:
# print(check2)
arr2.append(check2)
check2 += 1
result1 = len(arr1)
result2 = len(arr2)
# Checking which value is closer
if(result1 == result2):
print('Both numbers are equaly closer')
elif(result1 < result2):
print(f'The number {val1} is closer to {cond}')
else:
print(f'The number {val2} is closer to {cond}')