Hi, in ex33’s study drill, I can’t figure out how to make a function to substitute for-loop. Can anyone help me with it. I was able to make a function for the while-loop that I will put below with my rewritten code.
This is the function for while-loop.
This is the code I wrote when I used that function for the study drill.
How do we create a for-loop function for the exercise? And is my function and code alright? Can I do anything to improve it?
A simple for loop that use numbers would be:
for numbers in range(1, 50):
>> output =
You can also loop through a string:
a_fruit = 'banana'
for letters in a_fruit:
>> output =
I think w3schools have very good examples to learn from.
Right, thanks a lot. But didn’t the exercise say that we have to create a function which we can use in place of the for-loop? It did say to make a function for the while-loop which I did up there. Or I guess I wasn’t reading it carefully. Anyways, how can I improve the above scripts? Any suggestions? Thanks again
A better way to say that is “make a version of the while_loop function that uses a for-loop”. Not, “completely replace the concept of for-loops with functions”. However, you actually can do the latter:
if len(data) > 1:
See if you can figure that out.
Okay, now I understand! I also figured out your code. Line 1 calls a function. Now, line 2 prints whatever there is in the variable. Line 3 checks if the number of items in the variable or list is more than 1, then it executes the same function again but removes the first item of the list. Am I right? @zedshaw
Yep, so at the point where I print you could do any other code. This is a common pattern in a style of programming called “functional programming”. It uses the function as the main way to control looping rather than while or for.