Python Tutorial 4: if-else, for, while loop

Posted on Posted in Software

In the previous tutorial, we discussed variable, string and string operations. In this one, you know from the title that we will talk about conditional loops. So let’s begin.

The first one is if loop, where you can run if statement if a certain condition holds True, else they aren’t. Now, remember that Python uses indentation (i.e. the blank spaces) in order to delimit the blocks of code. This is equivalent to using the curly braces – {} in C, C++, Java.

If a condition doesn’t hold true and you want to move to the next condition, then you can write elif (which is the short form of else if) and when all the given conditions fail, the statements in the else loop is executed. You can also perform nested loop, i.e. if within if statement. Check the video for some examples.

Next, comes for loop. It is commonly used to repeat some code a certain number of times which can be done by combining with range objects. For example,

x=’being’
for x in range(len(x)-1):
print YouTuber

where len gives you the length of the string which is 5, so another inbuilt function you have encountered. And as a result, YouTuber is printed 4 times. I will discuss range in my next video. You can also write if statement in for loop. Check the video.

Finally, while loop.  The statement inside it is repeatedly executed as long as the condition holds. Once it evaluates to False, then the next section of code is executed. You can achieve infinite loop where the loop never stops running, i.e. condition remains true. To stop this, press ctrl+C. Also if you want to break out from a loop at any point, then use break where it ends the loop prematurely and immediately goes to the next section of code. Unlike break, continue helps you to jump back to the top of the loop, rather than stopping it.

So that’s it for tutorial 4 and I hope you have enjoyed it. So don’t forget to subscribe guys if you are new and hit the bell icon so that you don’t miss a single episode from us. Peace! 🙂

Spread it!

Leave a Reply