[英]Why is a line in my if statement running every time? (python)
I am working on a project were the user inputs a number and a list, and whatever item in the list is closest to the number, is printed out.我正在做一个项目,用户输入一个数字和一个列表,列表中最接近数字的任何项目都会被打印出来。 I have come across a problem were the line in my if() statement in my while loop is running every time?
我遇到了一个问题,我的 while 循环中的 if() 语句中的行每次都在运行吗? I have a feeling it has something to do with indenting if() statements in python 3 but I am not certain.
我觉得这与 python 3 中的 if() 语句缩进有关,但我不确定。 Anybody know why this is happening?
有人知道为什么会这样吗?
import math
MatchingI = math.inf
while i < len(compareList):
if (abs(int(mainNum) - int(compareList[i])) < MatchingI):
MatchingI = int(compareList[i])
i += 1
I think that you need to assign abs(int(mainNum) - int(compareList[i]))
to MatchingI
, instead of assigning int(compareList[i])
to MatchingI
.我认为您需要将
abs(int(mainNum) - int(compareList[i]))
分配给MatchingI
,而不是将int(compareList[i])
分配给MatchingI
。
import math
MatchingI = math.inf
while i < len(compareList):
if (abs(int(mainNum) - int(compareList[i])) < MatchingI):
MatchingI = abs(int(mainNum) - int(compareList[i]))
answer = compareList[i]
i += 1
print(answer)
Isn't this what you are looking for?这不是你要找的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.