In Python, do parameters still hold some value when the function call completes?
When a function call completes, all the parameters will no longer store any values in them.
Unlike regular variables we’ve worked with before, that were not parameters, parameters do not continue to reference some value after the function finishes running. Parameters are essentially “temporary placeholder variables”, so they only temporarily, for the duration of the function call, hold onto values, and reference them while the function is running. Once the function call completes entirely, the parameters will dereference any values and become “empty” again.
If you reassign the parameter name within the function, then within the function, that name will have its new value. Assuming that this is what you mean (please use the </> icon to post code),
print("From inside the function, ",parameter_name)
parameter_name = 5
print("This is the variable defined outside the function, ",parameter_name)
print("This is still the variable defined outside the function, ",parameter_name)
… the output would be:
This is the variable defined outside the function, 5
From inside the function, 7
This is still the variable defined outside the function, 5
Given you already have the code, surely you can run it, and then figure out what must have happened? Sometimes that is really useful to do, given then you figured it out, which is almost always better then an explanation.
@stetim94 is correct: Many of these things you can just try out for yourself.
Do you have Python installed on your computer? If so, try typing python into the shell. If you are lucky (i.e., if the path is set up correctly), you will get a Python shell to use.
If you don’t have Python installed, there are several online Python interpreters that you can use. TutorialsPoint has them for both Python2 and Python 3.
In addition, Python Tutor has an excellent tool that lets you visualize code execution step by step.
There are many others; I would certainly advocate getting into the habit of keeping one open at all times (when you are doing anything having to do with coding, of course!!), and using it as a scratchpad.
In this exercise can we assign more than one formal parameters while defining a function?
like in this example what if we also have one more greeting line that says
print("Todays sale special is " + Discount rate + “bars.”)
I am new to python but I tried the following and it worked fine.
def greet_customer(special_item, discount):
print(“Welcome to Engrossing Grocers.”)
print("Our special is " + special_item + discount + “.”)
print(“Have fun shopping!”
This will print "Hello World!" as the second parameter (arg2) is given a default value, if it’s not called. This article explains this very nicely, including some information on keyword arguments and arbitrary arguments.