Python 3 Tutorial for Beginners #05 – Python 3 While Loop

Python 3 while loop is very easy to use. Syntax is simpler than for loop and its usages are limitless.

Python 3 While Loop Syntax

Python 3 While Loop Syntax
Python 3 While Loop Syntax

From the above image, you can easily understand the Python 3 while loop syntax. Python language doesn’t need you to have parenthesis around the Boolean. I recommend that you don’t use the parenthesis as it enhances readability. Let’s see what happens when we run above code.

Python 3 While Loop Count 5 Times
Python 3 While Loop Count 5 Times

How to Loop Five Times

When I execute above code it prints “Hello World” five times. Let’s see how it happens.

Explanation of While Loop
Explanation of While Loop

While loop only executes if the condition evaluates to True.

Printing a Triangle

Let’s see an interesting example of while loop. It is pattern printing.

Python 3 Print Triangle
Python 3 Print Triangle

As you can see if you multiply a string by a number you get the string repeated.
Example: “A” * 3 will create “AAA”

In order to ensure that the stars are properly aligned number of spaces should be calculated. Let’s see how number of stars and spaces are calculated.

Calculate Triangle Characters
Calculate Triangle Characters

It is cool isn’t it. Number of spaces are calculated by subtracting counter from size. Also, number of stars are calculated by multiplying counter by 2 and subtracting 1. It is a good practice to define a reused value such as “5” (in this case) as a variable so it is easier to reuse. If someone uses an unknown number such as 5 all over the code it is harder for someone else to understand. Always name them so it is easier for others to read.

Now let’s go for an exercise to see if you really understand it.

Exercise: Print Below Pattern

*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********

Play with the provided code and try to come up with the answer yourself. You will need 2 while loops.

Answer

size = 5
counter = size
while counter > 0:
    spaces = " " * (size - counter)
    stars  = "*" * (counter * 2 - 1)
    print(spaces + stars)
    counter -= 1
counter += 2
while counter <= size:
    spaces = " " * (size - counter)
    stars  = "*" * (counter * 2 - 1)
    print(spaces + stars)
    counter += 1

That’s it for while loops. Also check out our Python 3 for loop guide.

Looking for more Python? Take a look at our Python tutorials for dabblers. We also have more Python tutorials for beginners. And while you’re here don’t forget to get the scoop on the latest tech news we’ve got just for you!

Like what you see? Subscribe to our email list and hit us with a like on our Facebook page to get the latest news updates and tutorials straight to your newsfeed!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.