how to change variable when a button connected to pin 2 is pressed
Go here --> Built-In Examples. Read the examples for Button, Debounce, and Digital Input Pullup. Digital Input Pullup is the best single one of those 3 I think, but read them all.

Those 3 are key.

Also, I wrote a buttonReader (debouncing) library here.

Sounds like you're a beginner, so check out Adafruit's tutorials here.

And lastly, I've compiled links to all my knowledge at the bottom of my article here.