You need to understand the concept of flow of control in python.. So lets take your code as an example.
So the flow of control would be something like this.
1 -> Line number one(defining your function and storing its reference in the RAM)
Remember, the flow of control will not move into the function as of now because the function in line 1 has just been defined, it hasn't been called yet.
2 -> Line number 3(assigning the variable)
3 -> Line number 4(Calling the function)
4 -> Line number 1 again(It will move onto the line number 1 as you called the function)
5 -> The code inside the function.
Now if you realize the variable has already been defined and assigned in the step 3. So the code inside your function recognizes the variable and does not produce any errors.