Example 4: Create a function that takes an argument. Give the function parameter a unique name. Show what happens when you try to use that parameter name outside the function. Explain the results.
Example 5: Show what happens when a variable defined outside a function has the same name as a local variable inside a function. Explain what happens to the value of each variable as the program runs.
def func(p,q):
n = p * q
return n
func(5,4)
20
p #As shown in the error message below p is not defined outside the function
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-ea80f99b01fd> in <module>
----> 1 p #As shown in the error message below p is not defined outside the function
NameError: name 'p' is not defined
name = 'David'
#The parameter has the same name as the variable
#The function will not use the variable
#passed into this parameter instead
def descr(name):
print('my name is {}'.format(name))
descr('Sarah')
#The value of the variable defined outside was unchanged
#This will print out 'David'
print(name)
my name is Sarah
David
Comments
Leave a comment