What happens if a parameter has the same name as a variable defined outside?


#1

Question

What happens when a parameter has the same name as a variable defined outside the function?

Answer

When a parameter has the same name as a variable defined outside, instead of the function using the variable defined outside, it will only reference the value that was passed to the parameter. So, parameters will be used over variables of the same name within a function.

Example

name = "Josh"

# The parameter has the same name as the variable above.
# The function will not use the variable's value, but the value
# passed into this parameter instead.
def sayHi(name):
  print("Hi, " + name + "!")

sayHi("Anne") 
# This will print out “Hi, Anne!”

# The value of the variable defined outside was unchanged.
# This will print out “Josh”.
print(name)