This question already has answers here:
What is the difference between a "function" and a "procedure"?
(18 answers)
Closed 1 year ago.
What the difference for function and Procedure in algorithm ??and how is it defined in python?
please,help me, I am a beginner in programming
In some languages, there is an explicit difference between the two. And the difference is not necessarily the same in all languages where such a difference exists.
In general, when such a distinction exists, it is implied that the function is 'pure', i.e. it always responds with the same output for the same input, and does not alter the state of the surrounding program. Whereas, a procedure, is more to be thought of as a list of commands, which may or may not take parameters, and operates on the existing space, possibly modifying it as a result.
In python there is no such distinction between 'function' and 'procedure', therefore the two can probably be used interchangeably, although presumably the term 'function' would be preferred.
Basically a function is something that calculates or executes a certain task (add a to b), while a procedure is a set of operations you perform in a certain order or depend on each other.
A function takes arguments and returns a value while a procedure does not return values it just performs a set of instructions.
In python they are both declared the same way using the def keyword and you either end it with a return statement if it's a function or not if it's a procedure
Here is an example of both :
function :
def add(a,b):
return a + b
procedure :
def printFullname(firstname,lastname):
print(firstname + ' ' + lastname)
Related
This question already has an answer here:
Why does setdefault evaluate default when key is set?
(1 answer)
Closed 6 months ago.
I don't understand the behavior of setdefault in this scenario:
def f(x):
return x+1
dct = {5: 15}
print(dct.setdefault(5, f(5)))
The key 5 is in the dictionary, but instead of returning the value 15 immediately, it wastes time computing the function at the second argument. In the end, it discards the output of f and returns 15.
Is this a bug? What is its purpose?
Python allows you to use expressions as parameters to a function. In fact, you could view all parameters as expressions. Python will evaluate all of the parameter expressions from left to right, resolving each to a single object. A function object is created, the list is expanded into the parameter set for the function, and finally the function is called.
In dct.setdefault(5, f(5)), python has no idea whether a function parameter expression will be used or not. And it can't evaluate the expression after the call is made. So, f(5) is resolved and the function is called.
If a function is expensive, then setdefault is not the tool for you. Use "not in" instead.
if 5 not in dct:
dct[5] = f(5)
In Python all arguments must be evaluated before the function is called. It would be a 'performant' behavior for this case, but could lead to consistency issues for others.
This question already has answers here:
Given a function with closure, can I refer back to it's closure scope?
(1 answer)
What exactly is contained within a obj.__closure__?
(4 answers)
Closed 2 years ago.
I would like to know if there is any method to check whether two functions have the same arguments at runtime in python 3.
Basically, I have this function (func) that takes another function and an argument. I want to check the values assigned to args in the lambda function
func(another_func, args):
return lambda(x : another_func(x, args))
It is not feasible to run the code before and check the results because I am implementing a lazy framework. My main goal is to be able to understand what are the arguments of the function because there is one variable argument that I do not care but there is one static that is created before running the function.
##EDIT
I actually solved this problem using the inspect module (getclosure) for those who are interested!
I actually solved this problem using the inspect module (getclosure) for those who are interested!
Extension (Martijn Pieters):
I think you are referring to getclosurevars(). You can also just access function.closure, and access the value of each cell via its cell_contents attribute.
This question already has answers here:
What are variable annotations?
(2 answers)
Closed 3 years ago.
I just came across this function:
def splitComma(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
return "{}, {}".format(splits[1], splits[2])
I am aware that you can separate parameters by , or can set a value within a parameter like a=39 but I have not seen a colon like line:str. I have checked the function definition online but could not find anything like this. What does this colon mean?
It's a function annotation; function arguments and the return value can be tagged with arbitrary Python expressions. Python itself ignores the annotation (other than saving it), but third-party tools can make use of them.
In this case, it is intended as type hint: programs like mypy can analyze your code statically (that is, without running it, but only looking at the source code itself) to ensure that only str values are passed as arguments to splitComma.
A fuller annotation to also specify the return type of the function:
def splitComma(line: str) -> str:
...
(Note that originally, function annotations weren't assumed to have any specific semantics. This is still true, but the overwhelming assumption these days is that the annotations provide type hints.)
This is a type annotation used by static analysis tools to check, well, types. It helps ensure program correctness before you run the code.
This question already has answers here:
nargout in Python
(6 answers)
Closed 7 years ago.
In Python, do functions know how many outputs are requested? For instance, could I have a function that normally returns one output, but if two outputs are requested, it does an additional calculation and returns that too?
Or is this not the standard way to do it? In this case, it would be nice to avoid an extra function argument that says to provide a second input. But I'm interested in learning the standard way to do this.
The real and easy answer is: No.
Python functions/methods does not know about how many outputs are requested, as unpacking of a returned tuple happens after the function call.
What's quite a best practice to do though is to use underscore (_) as a placeholder for unused args that are returned from functions when they're not needed, example:
def f():
return 1, 2, 3
a, b, c = f() # if you want to use all
a, _, _ = f() # use only first element in the returned tuple, 'a'
_, b, _ = f() # use only 'b'
For example, when using underscore (_) pylint will suppress any unused argument warnings.
Python functions always return exactly 1 value.
In this case:
def myfunc():
return
that value is None. In this case:
def myfunc():
return 1, 2, 3
that value is the tuple (1, 2, 3).
So there is nothing for the function to know, really.
As for returning different outputs controlled by parameters, I'm always on the fence about that. It would depend on the actual use case. For a public API that is used by others, it is probably best to provide two separate functions with different return types, that call private code that does take the parameter.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 8 years ago.
So what I'm trying to do is run a function using concatenation like this:
location = 1
"critter_" + location + "()"
and I was hoping that would run the function 'critter_1()' but apparently it doesn't work like that so I tried a couple of stuff since it gave me an error about str to int concatenation error. So what I tried was:
location = 1
"critter_" + int(location) + "()"
And it still didn't work so I came here to ask you guys if there is any way to actually do this.
Any ideas? Thanks!
You can use globals()[function_name] to get function object. Once you get the function object, call it like ordinary name.
func = globals()['critter_{}'.format(location)]
# OR func = globals()['critter_' + str(location)]
func()
You have two separate problems:
You need to get the correct name for the function, so you need to convert your integer 1 to the string '1'. The easiest way is to just use funcname = "critter_"+str(location), although you have more control over the way the conversion is done if you use the format method of the strings. (You've got the meaning of int almost exactly backwards -- it converts to an integer; str converts to a string!)
You need to call the function given by the string. For this, you can use a number of different methods. Simplest is probably just to call eval(funcname+"()"), although this isn't always safe. You can also use funcname to find the function in the dictionary which stores all globally defined function, globals()[funcname].
Alternately, you could make your own list or dictionary of critter_n functions, and select from that:
critter_functions = {1: critter_1, 2: critter_2} #etc...
# ...
location = 1
critter_functions[location]()