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

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)
29 Likes

This concept is called shadow a variable. i.e, the argument passed to a formal parameter shadow the variable defined globally.

21 Likes

In the exercise below:

current_year=2048
def calculate_age(birth_year):
age = current_year - birth_year
return age
print(current_year)
print(calculate_age(1970))

when we print calculate_age(1970), how does the function takes into account “age=current_year-birth_year” as calculate_age only has the birth_year?. How does print function know that we have to subtract birth_year from current_year?.

1 Like

A variable declared in global scope can be polled from inside any function. current_year is global and as such accessible to current_age().

8 Likes

Awesome response! Thank you.

very nice explanation.

Isn’t this a bad idea since it creates one more thing for a maintenance developer to figure out?