Help with Ex33 study drill

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.
Capture
This is the function for while-loop.

Capture1
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?

Hello @CodeNinja
A simple for loop that use numbers would be:

for numbers in range(1, 50):
    print(numbers)
>> output = 
1
2
3
...

You can also loop through a string:

a_fruit = 'banana'
for letters in a_fruit:
    print(letters)

>> output =

b
a
n
a
n
a

I think w3schools have very good examples to learn from.

1 Like

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 :blush:
@ulfen69

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:

def for_each(data):
   print(data)
   if len(data) > 1:
      for_each(data[1:])

See if you can figure that out.

1 Like

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 :thinking:

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.

1 Like