1

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

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

4 Comments

@Aaron I think you need two variables, one is for the difference and the other is for something like whether it is larger or less.
It's more probable (by the naming convention) that they want MatchingI = i and the comparison to be < abs(int(mainNum) - int(compareList[MatchingI])).
@Naetmul I didn't see the code part it glitched out and I didn't see the code part, sorry ._.
@MarkRansom Yes with MatchingI = 0 for initialization

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.