Conditionals and Loops in Python: Learn how to use them together

03:05
conditionals and loops in Python

Conditionals and Loops in Python: Learn how to use them together

03:05

Next Video: An example of skewness

Conditional

Let’s see how to combine conditionals and loops in Python.

To print all the values from 2 to the power of 0, 2 to the power of 1, and so on, until 2 to the power of 9, we can use the following code: for “n” in range of 10, print “2 double star n”. I will also have to insert a comma, because I would like to see the output on a single line.

I guess you can agree it was not necessary to specify the name of a list that exists in our code – using a list created through the “range” function is going to work too!

Now, let’s be brave and create an iteration that includes a conditional in the loop body. We can tell the computer to print all the even values between 0 and 19 and state “Odd” in the places where we have odd numbers.

Let’s translate this into computational steps and learn how to combine conditionals and loops in Python.

If x leaves a remainder of 0 when divided by 2, which is the same as to say “if x is even”, then print x on the same line. “Else”, which means unless x is even, or if x is odd, print “Odd”.

Lovely! This is an example of a combination of an iteration and a conditional in Python.

There are two main ways to program a loop, and until this moment, we paid attention only to the first one.

We have a list x that contains the numbers 0, 1, and 2. We saw we can print out each of its elements by typing “for each item in the x list, print out that item”.

The second way finds its practical application in more sophisticated codes. Its structure takes advantage of the range and len functions in the following way: “for each item in a range that goes through the elements from the list x, that is “len with an argument x”, print out each item”.

If we do this, the variable item will loop through a new list created by range, and that has as many elements as the x list itself.

Please note that, in this situation, the second line of our code needs indexing to extract each item from the “x” list.

In practice, we will print out the element at position 0 from the list x, then the element at position 1, and finally the element at position 2.

To conclude, both approaches can lead to the same outcome. Although the second one looks unnecessarily complicated, in advanced coding, it might turn out to be a lot more useful. So, it is important you know both.

Hope that you liked our lesson on how to combine conditionals and loops in Python.

Eager to learn more? Check out our Python for Finance: Investment Fundamentals and Data Analytics course here.

Leave a Reply

Your email address will not be published.

A Free Data Science Career Guide?

Check your email shortly!