A floating pin
A button joins pin 2 to ground (GND, 0 volts). With the button open, the pin is connected to nothing at all. We call it floating, and digitalRead returns 0 or 1 at random.
An input pin draws almost no current: at most 1 µA, a millionth of an amp. Engineers call this high impedance. So stray charge from a nearby wire or your finger is enough to swing its voltage up and down.
The pull-up resistor
Add a 10 kΩ resistor from the pin to 5 V: a pull-up. With the button open almost no current flows, so the resistor drops almost no voltage. The pin sits at 5 V and reads HIGH, 1.
Press the button. The pin is now joined straight to ground, so it sits at 0 V and reads LOW, 0. Current flows from 5 V through the resistor and button to ground: 5 V ÷ 10 kΩ = 0.5 mA.
With a pull-up the logic is upside down: open reads HIGH, pressed reads LOW. Engineers call this negative logic. So the code checks for LOW: line 4 lights the LED on pin 13 while v is LOW.
Why not tie the pin to 5 V with a plain wire? Then pressing the button joins 5 V straight to ground: a short circuit, with a huge current. With a 10 kΩ resistor instead, a press draws a safe 0.5 mA.
Too small wastes current: 1 kΩ draws 5 mA on every press. Too big is weak: with 1 MΩ, the pin's own 1 µA leak could drop 1 V, and noise gets in. 10 kΩ is the usual choice.
Built in, and flipped
The ATmega328P has a pull-up built into every pin. pinMode(2, INPUT_PULLUP) switches it on, so the outside resistor can go. It is weaker, 20 to 50 kΩ, so a press draws only 0.1 to 0.25 mA.
Swap them: button to 5 V, resistor to ground. Now the resistor pulls the pin down to 0 V, and a press reads HIGH. The ATmega328P has no pull-downs inside, but an ESP32 does: INPUT_PULLDOWN.
What happens
;; step 1/9 · floating board Arduino Uno R3 (ATmega328P, 5 V) wiring pin 2 -> button -> GND line 1 pinMode(2, INPUT); open pin joined to nothing: floating read 0, 1, 1, 0, ... at random
The figure shows the voltage the pin itself sees. A real multimeter has an input resistance of millions of ohms, so touching a floating pin with it pulls the pin a little and changes the reading. 1 µA is the datasheet's worst case for input leakage (at 5.5 V). A real pin usually leaks far less, so with 10 kΩ the open pin sits within 0.01 V of 5 V.