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? I have a feeling it has something to do with indenting if() statements in python 3 but I am not certain. 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
.
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.