Wednesday, 5 July 2017

How to become a Python Jedi - Beginners Python Programming Tutorial - Part 6 - While Loop

Welcome back friends to another post on TheCodingProject and we are back with the sixth chapter of the Beginner Python programming tutorial - How to become a python Jedi. This time we are going to learn about the while statement.

The While Loop statement?
In Python Programming, There are 3 types of loops →

  • While loop
  • For loop
  • Nested loops

Now to get into some action→

Let’s consider that two groups of aliens have landed on earth  out of these two one of the group is good & the other are the bad guys. The govt. Has given you the task of designing a system that takes in input from different eyewitnesses & then classify that whether the aliens that these eyewitnesses encounter are the good guys or bad guys.

Copy & paste the above code in your editor and run this code. What do you get ? When the input is Autobots it matches the condition aliens == "Autobots" & it enters the loop to prints the statement pointed by the print method.

We can also use negative conditions for entering the while loop. Copy and paste the below code in your editor and run it→

As you can see the condition aliens is not "Autobots" resolves to False when the user inputs a wrong condition & the control enters the loop and print the statement when a false condition is returned.

Now let’s make our system a bit more robust by adding some extra checks into it. We shall insert an if statement inside our while loop. In the version below if user gives the first input as Decepticons then the control enters the loop & prompts user for second input. Again if the input is Megatron then the control enters the if condition to print the last statement.

So, folks this was all for this week but we shall return with another chapter of this tutorial with some new concepts to learn.

Subscribe to my youtube channel to watch the coding in this tutorial in action.

If you have any questions, suggestions or comments you can post your comment here or you can also bug me on Quora, Twitter or on Facebook.