Photo by Will H McMahan on Unsplash

Yielding Values From a While Loop

George Reyes
3 min readJan 26, 2021

--

This article should help you get familiar with yielding values from a loop.

To show how to do this I made a function that iteratively calculates the derivate of a power function f(x). To get started open up your Python editor and define a function: get_derivative() that will take in a (constant) and a variable (x) by copying the code below. The (z) variable will serve to count the degrees of derivatives that were calculated.

Notice how we have our while loop setup and the logic below it. What we are stating here is the aX^n to n(aX)^n-1 derivative power rule. At the bottom of our code block we have our yield statement yielding our constant, x and z values.

This yield statement comes in handy here by outputting (constant, x, and z) while x is > 0. Now copy function: f_of_x() that takes in (constant) and (var1). Once you’ve done that, before continuing to read see if you can understand the logic below, it’s an if statement so you might be familiar with it already.

Here we are checking to see if the exponent of var1 is 0 then return your constant, if its greater than or equal to one then send that value to our get_derivative() function, else then we have an edge case. To get started An example would be 4x³ (you may also see 4x**3). Here we would have (4*3) and (3–1) to yield 12x². Can you guess what (z) is at this stage?…the answer is 1, since we only took the first degree derivate also denoted as: f’(x).

Something to note here is that under “if var1 >= 1” we are looping through our get derivative function. This is so we may access the values being outputted by the yield statement.

Now we are done with the function and you are ready to print some results! Copy the code below then run: python3 nameOfyourFile.py in your terminal. After you run it type in: 4 3 in your terminal not separated by a comma, since we are using split to split our inputs by the whitespace in the middle.

After you run it you should get: 4 3

1 Degree Derivative: 12 x**2

2 Degree Derivative: 24 x**1

3 Degree Derivative: 24 x**0

As your output. Try this example again with different numbers and follow the logic while calculating the derivative yourself see if you can follow the inputs being piped from one function to another. The important concept here is for you to learn how to pipe values from a loop and insert them into another function so that you can add more logic as needed.

When going through tutorials like these, generic examples are usually provided because the example is arbitrary. The real power comes from you being able to apply these concepts in the “real” world and not just for some fizz buzz problem.

For similar projects follow me on GitHub at: https://github.com/reyesGeorge

--

--

George Reyes

Software engineer with experience in Python, TypeScript and Dart.