Code doesn't work

So my code should look like this?

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

local character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local distanceMin
local distance = 3
local closestPlayer

UserInputService.InputBegan:Connect(function (input, IsTyping)
	if input.KeyCode == Enum.KeyCode.E and IsTyping == false then
		distanceMin = math.huge
		for _, player in pairs(Players:GetPlayers()) do
			if distanceMin < 3 then
				print(closestPlayer.Name .. " is the closest player.")
			end
		end
	end
end)

or do I add it after

if player ~= LocalPlayer then

I feel like I did something wrong.

rather like this

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

local character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
local head = character:WaitForChild("Head")
local distanceMin
local distance
local closestPlayer


UserInputService.InputBegan:Connect(function (input, IsTyping)
	if input.KeyCode == Enum.KeyCode.E and IsTyping == false then
		distanceMin = math.huge
		for _, player in pairs(Players:GetPlayers()) do
			if player ~= LocalPlayer then
				distance = player:DistanceFromCharacter(head.Position)
				if distance < distanceMin then
					distanceMin = distance
					closestPlayer = player
				end
			end
		end
		--print(closestPlayer.Name .. " is the closest player.")

		if distanceMin < 3 then -- 3 is your minimum distance
			print(closestPlayer.Name .. " is the closest player.")
		end
	end
end)

Yay! thanks! now I just need to examine this to see if I can understand it

It is also worth mentioning that your way of getting magnitude is also wrong, you just subtract the torso’s position from the magnitude and then check. You need to subtract both positions, get the magnitude of the result and then check.