9. The Closest Restaurant

Screen Link:

My Code:

# provided input
x = 100
y = 100 
# answer to this input: LEADBETTERS II

from csv import reader
import math
def distance(x_1, y_1, x_2, y_2):
    return math.sqrt((x_1 - x_2)**2 + (y_1 - y_2)**2)

def closest_restaurant(x,y):
    opened_file = open('restaurants.csv')
    read_file = reader(opened_file)
    restaurants_csv = list(read_file)
    restaurants_csv = restaurants_csv[1:]
    minimum = None
    closest_name = None
    for row in restaurants_csv:
        rest_name = row[0]
        x_cor = int(row[3])
        y_cor = int(row[4])
        if minimum is None or distance(x_cor, y_cor, x, y) < minimum:
            minimum = distance(x_cor, y_cor, x, y)
            closest_name = rest_name
    return closest_name

Why do we have to declare closest_name=rest_name in the if line? Can’t we just delete that part of the code and in the final line of the function, replace it with return rest_name? I need more clarity on the if statement overall as well.

@TravisBob: This has got to do with the concept of scope. rest_name is defined inside the for loop. Once the loop terminates, the variable will be discarded. Since you defined closest_name outside the loop, the value in rest_name can be stored and returned to the main program using the return statement when the function is called.