How Does a Function in a Loop (Which Returns Another Function) Work

How does a function in a loop (which returns another function) work?

When you assign the function to the click handler, a closure is created.

Basically a closure is formed when you nest functions, inner functions can refer to the variables present in their outer enclosing functions even after their parent functions have already executed.

At the time that the click event is executed, the handler refers to the last value that the i variable had, because that variable is stored on the closure.

As you noticed, by wrapping the click handler function in order to accept the i variable as an argument, and returning another function (basically create another closure) it works as you expect:

for ( var i = 0; i < 4; i++ ) {
var a = document.createElement( "a" );
a.onclick = (function(j) { // a closure is created
return function () {
alert(j);
}
}(i));
document.getElementById( "foo" ).appendChild( a );
}

When you iterate, actually create 4 functions, each function store a reference to i at the time it was created (by passing i), this value is stored on the outer closure and the inner function is executed when the click event fires.

I use the following snippet to explain closures (and a very basic concept of curry), I think that a simple example can make easier to get the concept:

// a function that generates functions to add two numbers
function addGenerator (x) { // closure that stores the first number
return function (y){ // make the addition
return x + y;
};
}

var plusOne = addGenerator(1), // create two number adding functions
addFive = addGenerator(5);

alert(addFive(10)); // 15
alert(plusOne(10)); // 11

Calling a function in a loop of another function

There are a couple of options here. If you have python 3.8+, you can use the walrus operator (:=) to put api_call directly in the condition of the loop:

def unpack_response():
while "meta" not in (api_response := api_call()):
id_value = "id"
res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
id_value = "".join(res1)
percent_value = "percent_complete"
res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')
return api_response

A more traditional, but no less idiomatic method is to run the loop forever and break when the correct condition is reached:

def unpack_response():
while True:
api_response = api_call()
if "meta" in api_response:
return api_response
id_value = "id"
res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
id_value = "".join(res1)
percent_value = "percent_complete"
res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')

In both cases, you might consider slowing down the rate at which you make API calls with a sleep or similar.

How can I use `return` to get back multiple values from a loop? Can I put them in a list?

Using a return inside of a loop will break it and exit the function even if the iteration is still not finished.

For example:

def num():
# Here there will be only one iteration
# For number == 1 => 1 % 2 = 1
# So, break the loop and return the number
for number in range(1, 10):
if number % 2:
return number
>>> num()
1

In some cases we need to break the loop if some conditions are met. However, in your current code, breaking the loop before finishing it is unintentional.

Instead of that, you can use a different approach:

Yielding your data

def show_todo():
# Create a generator
for key, value in cal.items():
yield value[0], key

You can call it like:

a = list(show_todo())  # or tuple(show_todo())

or you can iterate through it:

for v, k in show_todo(): ...

Putting your data into a list or other container

Append your data to a list, then return it after the end of your loop:

def show_todo():
my_list = []
for key, value in cal.items():
my_list.append((value[0], key))
return my_list

Or use a list comprehension:

def show_todo():
return [(value[0], key) for key, value in cal.items()]

How to return a complete for Loop in a function

After return is run, the function stops evaluating. If you'd like to return everything in a for loop, return a list of its outputs:

ret_vals = []
for x in value:
ret_vals.append(x)

return(ret_vals)

You can print them on new lines like you specified like so:

out = func()
for x in out:
print(x)

How to use function inside for loop of another function into python

Well you can define function by self. Just add self in all functions and then you can use:

def previous_and_next(self,some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return zip(prevs, items, nexts)

Property = self.previous_and_next(employee_list)

How do i loop a function from another function in c++

I just updated your code to create a minimal example.This is just to show you how it is done.
I just called the function where you are printing the values. As you are passing arguments by ref. all you had to do is to call the function with different inputs and the value of Farenheit variable will be changed in the loop. and you can print that new value associated with the input.

#include <iostream>

#include <iomanip> using namespace std;

int user_interface();
void convert(double & , double & );
void print_table(double, double & );

int main(int argc, char * argv[]) {
user_interface();
/*convert(Farenheit);*/

return 0;
}

int user_interface() {
double user_input;
double Farenheit;

do {
cout << "Please Enter Maximum Kelvin Value: ";
cin >> user_input;
if (user_input < 0) {
cout << "Positive Integer Values Only! Please Try Again.\n";
}

} while (user_input <= 0);

print_table(user_input, Farenheit);

return 0;
}

void convert(double & temp, double & Farenheit) {
Farenheit = ((9 * (temp - 273.15)) / 5) + 32;
}

void print_table(double user_input, double & Farenheit) {
double x;

cout << "Temp_user_input" << Farenheit << "\n";

cout.width(10);
cout << "K";
cout.width(14);
cout << "F" << "\n";

for (x = 0; x <= user_input; x += 50) {
cout.width(10.2);
cout << x;
cout.width(14.2);
convert(x, Farenheit);
cout << Farenheit << "\n";
}
}

Trouble Calling a Function Within the For Loop of Another Function

First of all, you need to supply fileName in the parseExtension function call. But then you have some more issues. I think what you want is this.

def parseExtension(filename):
periodPosition = filename.find(".")
extension = (filename[periodPosition + 1:])
return extension

def fileExtensionExists(fileList, fileExtension):
for fileName in fileList:
if parseExtension(fileName) == fileExtension:
return True
return False

my_files = ["python.exe", "assignment5.docx", "assignment4.py",
"shortcuts.docx", "geographyhw1.txt"]

print(fileExtensionExists(my_files, "py"))

How can I use `return` to get back multiple values from a loop? Can I put them in a list?

Using a return inside of a loop will break it and exit the function even if the iteration is still not finished.

For example:

def num():
# Here there will be only one iteration
# For number == 1 => 1 % 2 = 1
# So, break the loop and return the number
for number in range(1, 10):
if number % 2:
return number
>>> num()
1

In some cases we need to break the loop if some conditions are met. However, in your current code, breaking the loop before finishing it is unintentional.

Instead of that, you can use a different approach:

Yielding your data

def show_todo():
# Create a generator
for key, value in cal.items():
yield value[0], key

You can call it like:

a = list(show_todo())  # or tuple(show_todo())

or you can iterate through it:

for v, k in show_todo(): ...

Putting your data into a list or other container

Append your data to a list, then return it after the end of your loop:

def show_todo():
my_list = []
for key, value in cal.items():
my_list.append((value[0], key))
return my_list

Or use a list comprehension:

def show_todo():
return [(value[0], key) for key, value in cal.items()]


Related Topics



Leave a reply



Submit