[Python] Why does the first program return the closest number , while the second doesn't?

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    # Python implementation to find the number closest to n
    # and divisible by m
    def closest_number(n, m):
    # find the quotient
    closest = 0
    min_difference = float('inf')

    # Check numbers around n
    for i in range(n - abs(m), n + abs(m) + 1):
    if i % m == 0:
    difference = abs(n - i)

    if difference < min_difference or \
    (difference == min_difference and abs(i) > abs(closest)):
    closest = i
    min_difference = difference
    return closest

    n = 13
    m = 4
    print(closest_number(n, m))


    code that I have written

    def closestNum(n,m):
    closest = 0
    minDiff = float('inf')
    for i in range (n - abs(m), n + abs(m) + 1):
    if n % i == 0:
    diff = abs(n - i)
    if diff < minDiff or \
    diff == minDiff and abs(i) > abs(closest):
    closest = i
    minDiff = diff
    return closest

    n = 4
    m = 13
    print(closestNum(n,m))



    UnboundLocalError: cannot access local variable 'diff' where it is not associated with a value

    I want to know that what is the concept that I am not aware of . Because i wrote the second program on my own, and I want to know how to get the closest num, it's similar to the first program. Chat Gpt says define the difference variable before the loop, but in the first method it's not defined outside the loop. So that's why I was really curious to know about how can I make the program work.

    Continue reading...

Compartilhe esta Página