Answer to Question #236337 in Python for Ashkan

Question #236337

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.


1
Expert's answer
2021-09-12T22:59:18-0400
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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS