Python while Loop Programs with Pattern Examples for Beginners 2026

Learn Python Loops: while Loop, range(), break, continue & pass Explained 

Learn Python Loops for Beginners

while Loop in Python

Introduction

Pattern programs are one of the best ways to understand how loops work in Python. While most pattern programs are written using nested for loops, they can also be created using nested while loops. Writing patterns with while loops helps beginners understand loop conditions, counters, and nested iterations more deeply.

A while loop repeatedly executes a block of code until its condition becomes False.

The loop first checks the condition.

  • If the condition is True, the code executes.
  • After execution, the condition is checked again.
  • The process continues until the condition becomes False.

A while loop repeats a block of code as long as a specified condition is True. By carefully controlling the row and column counters, we can create different star, number, and alphabet patterns.


·        Python While Loop Syntax

       while condition:

    # Code to execute repeatedly

Syntax Explanation

  • while – The keyword that starts the loop.
  • condition – A Boolean expression (True or False) checked before each iteration.
  • Indented block – The statements inside the loop. Python uses indentation to define the loop body.
  • Condition update – Make sure the variable used in the condition is updated inside the loop; otherwise, the loop may run indefinitely (an infinite loop).

Example

count = 1 

while count <= 5:

    print("Count:", count)

    count += 1

Output

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

How the Syntax Works

  1. Initialize a variable before the loop.
  2. Python checks the condition.
  3. If the condition is True, the code inside the loop executes.
  4. Update the loop variable.
  5. Python checks the condition again.
  6. The loop continues until the condition becomes False

Python While Loop Flowchart

             Start

               |

             

      Initialize Variable

               |

             

      Check Condition?

         /          \

      Yes            No

       |              |

                  

 Execute Statements   End

       |

     

 Update Variable

       |

       └────────────── Back to Condition

Program Syntax

row = 1

 while row <= number_of_rows:

     column = 1

     while column <= number_of_columns:

        print("*", end=" ")

        column += 1

     print()

    row += 1

Explanation

  • The outer while loop controls the number of rows.
  • The inner while loop controls the number of columns.
  • print("*", end=" ") prints stars on the same line.
  • print() moves the cursor to the next line.
  • Both row and column counters are increased manually.

Pattern 1: Square Star Pattern

Program

rows = 5

 i = 1

 while i <= rows:

     j = 1

     while j <= rows:

        print("*", end=" ")

        j += 1

     print()

    i += 1

Output

* * * * *

* * * * *

* * * * *

* * * * *

* * * * *

Explanation

  • Outer loop runs 5 times.
  • Inner loop prints 5 stars in each row.
  • After each row, the cursor moves to the next line.

How While Loop Works

Step 1

Initialize the variable.

i = 1

Step 2

Check the condition.

while i <= 5:

Step 3

Execute the statements.

print(i)

Step 4

Update the variable.

i += 1


Example 1: Print Numbers 1 to 5

i = 1

 while i <= 5:

    print(i)

    i += 1

Output

1

2

3

4

5

Pattern 2: Right Triangle Star Pattern

Program

rows = 5

 i = 1

 while i <= rows:

     j = 1

     while j <= i:

        print("*", end=" ")

        j += 1

 

    print()

    i += 1

Output

*

* *

* * *

* * * *

* * * * *

Explanation

  • Row 1 prints 1 star.
  • Row 2 prints 2 stars.
  • Row 3 prints 3 stars.
  • The number of stars increases with each row.

Pattern 3: Inverted Right Triangle

Program

rows = 5

 i = rows

 while i >= 1:

     j = 1

     while j <= i:

        print("*", end=" ")

        j += 1

     print()

    i -= 1

Output

* * * * *

* * * *

* * *

* *

*

Explanation

  • Starts with 5 stars.
  • Decreases by one star after every row.

Pattern 4: Number Triangle

Program

rows = 5

 i = 1

 while i <= rows:

     j = 1

     while j <= i:

        print(j, end=" ")

        j += 1

     print()

    i += 1

Output

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

Explanation

Each row prints numbers starting from 1 up to the current row number.


Pattern 5: Repeated Number Triangle

Program

rows = 5

 i = 1

 while i <= rows:

     j = 1

     while j <= i:

        print(i, end=" ")

        j += 1

     print()

    i += 1

Output

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

Explanation

The current row number is printed repeatedly.


Pattern 6: Floyd's Triangle

Program

rows = 5

 i = 1

num = 1

 while i <= rows:

     j = 1

     while j <= i:

        print(num, end=" ")

        num += 1

        j += 1

     print()

    i += 1

Output

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

Explanation

A separate variable num stores the next number to print. It increases after every printed value.


Pattern 7: Alphabet Triangle

Program

rows = 5

 i = 1

 while i <= rows:

     j = 1

    ch = 65

     while j <= i:

        print(chr(ch), end=" ")

        ch += 1

        j += 1

     print()

    i += 1

Output

A

A B

A B C

A B C D

A B C D E

Explanation

  • ASCII value 65 represents A.
  • chr() converts the ASCII value into a character.
  • Each row starts again from A.

Pattern 8: Multiplication Table (5)

Program

i = 1

 while i <= 10:

    print("5 x", i, "=", 5 * i)

    i += 1

Output

5 x 1 = 5

5 x 2 = 10

5 x 3 = 15

5 x 4 = 20

5 x 5 = 25

5 x 6 = 30

5 x 7 = 35

5 x 8 = 40

5 x 9 = 45

5 x 10 = 50


Pattern 9: Hollow Square

Program

rows = 5

 i = 1

 while i <= rows:

     j = 1

     while j <= rows:

         if i == 1 or i == rows or j == 1 or j == rows:

            print("*", end=" ")

        else:

            print(" ", end=" ")

         j += 1

     print()

    i += 1

Output

* * * * *

*       *

*       *

*       *

* * * * *

Explanation

  • The border prints *.
  • The inside prints spaces.

Pattern 10: Reverse Number Pattern

Program

rows = 5

 i = rows

 while i >= 1:

     j = i

     while j >= 1:

        print(j, end=" ")

        j -= 1

     print()

    i -= 1

Output

5 4 3 2 1

4 3 2 1

3 2 1

2 1

1


Advantages of Using while Loops for Pattern Programs

  • Improves understanding of loop conditions.
  • Strengthens knowledge of counters and iterations.
  • Helps build problem-solving skills.
  • Demonstrates manual control over loop execution.
  • Builds a strong foundation for nested loops and algorithms.

Common Mistakes

  • Forgetting to increment (i += 1 or j += 1), which can create an infinite loop.
  • Initializing the inner loop counter outside the outer loop, causing incorrect output.
  • Using the wrong loop condition (< instead of <=).
  • Incorrect indentation, leading to IndentationError.

Conclusion

Pattern programs using the while loop are an excellent way to master nested loops and understand how iteration works in Python. Although for loops are often simpler for pattern printing, practicing with while loops develops a deeper understanding of loop control, counters, and conditions. Once you're comfortable with these examples, try creating your own star, number, and alphabet patterns to strengthen your programming skills.

 

Python range() Function

Introduction

The range() function is one of the most commonly used built-in functions in Python. It is mainly used with the for loop to generate a sequence of numbers automatically. Instead of writing numbers manually, range() creates them for you, making your code shorter, cleaner, and more efficient.

The range() function does not create a list directly. Instead, it returns a range object, which generates numbers only when needed. This makes Python programs more memory-efficient, especially when working with large sequences.

For example, if you want to print numbers from 1 to 100, writing 100 print() statements would be unnecessary. With range(), you can do it in just a few lines of code.


Syntax

range(stop)

range(start, stop)

range(start, stop, step)

Parameters

  • start – Starting number (default is 0)
  • stop – Ending number (not included)
  • step – Difference between consecutive numbers (default is 1)

Example 1

for i in range(5):

    print(i)

Output

0

1

2

3

4

Explanation

The loop starts from 0 because the default starting value is 0. It stops before 5.


Example 2

for i in range(1, 6):

    print(i)

Output

1

2

3

4

5


Example 3

for i in range(2, 11, 2):

    print(i)

Output

2

4

6

8

10


Example 4

for i in range(10, 0, -1):

    print(i)

Output

10

9

8

7

6

5

4

3

2

1


Python break Statement

What is break?

The break statement is used to terminate a loop immediately. As soon as Python encounters a break statement, the loop stops, and the program continues with the next statement after the loop.

Syntax

break


Example:1

for i in range(1, 11):

 

    if i == 6:

        break

     print(i)

Output

1

2

3

4

5

Explanation

The loop stops when the value becomes 6.


Real-Life Example

Searching for a student in a class list.

Once the student is found, there is no need to search further.


Python continue Statement

What is continue?

The continue statement skips the current iteration and immediately moves to the next iteration of the loop.

Unlike break, it does not terminate the loop.


Example:1

for i in range(1, 6):

     if i == 3:

        continue

 

    print(i)

Output

1

2

4

5

Explanation

Number 3 is skipped, but the loop continues.


Example:2

Print only odd numbers.

for i in range(1, 11):

     if i % 2 == 0:

        continue

     print(i)

Output

1

3

5

7

9

Python Variables and Data Type


Python pass Statement

What is pass?

The pass statement is a placeholder statement.

It does absolutely nothing.

It is useful when writing incomplete code.


Syntax

pass


Example :1

for i in range(5):

     if i == 2:

        pass

     print(i)

Output

0

1

2

3

4

Explanation

When i becomes 2, Python executes pass, which has no effect.


Example

def student():

    pass

The function is empty but does not produce an error.


Difference Between break, continue, and pass

Statement

       Purpose

          Effect

break

       Exit the loop

          Stops loop immediately

continue

       Skip current iteration  

          Continues next iteration

pass

       Placeholder

          Does nothing


Nested Loops in Python

What is a Nested Loop?

A nested loop means placing one loop inside another loop.

The outer loop executes first.

For every iteration of the outer loop, the inner loop runs completely.

Nested loops are mainly used for:

  • Pattern programs
  • Matrix operations
  • Tables
  • Games
  • Searching

Syntax

for i in range(rows):

     for j in range(columns):

         print("*", end=" ")

     print()


Example

for row in range(3):

     for column in range(4):

        print("*", end=" ")

     print()

Output

* * * *

* * * *

* * * *


How Nested Loops Work

Outer Loop

Row 1

    Inner Loop → ****

 Row 2

    Inner Loop → ****

 Row 3

    Inner Loop → ****

The inner loop finishes completely before the outer loop moves to the next row.


Pattern 1 – Square Pattern

for i in range(5):

     for j in range(5):

        print("*", end=" ")

     print()

Output

* * * * *

* * * * *

* * * * *

* * * * *

* * * * *


Pattern 2 – Right Triangle

for i in range(1, 6):

     for j in range(i):

        print("*", end=" ")

     print()

Output

*

* *

* * *

* * * *

* * * * *


Pattern 3 – Inverted Triangle

for i in range(5, 0, -1):

     for j in range(i):

        print("*", end=" ")

     print()

Output

* * * * *

* * * *

* * *

* *

*


Pattern 4 – Number Triangle

for i in range(1, 6):

     for j in range(1, i + 1):

        print(j, end=" ")

     print()

Output

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5


Pattern 5 – Repeated Number Pattern

for i in range(1, 6):

     for j in range(i):

        print(i, end=" ")

     print()

Output

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5


Pattern 6 – Floyd's Triangle

num = 1

 for i in range(1, 6):

     for j in range(i):

        print(num, end=" ")

        num += 1

     print()

Output

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15


Pattern 7 – Alphabet Pattern

for i in range(1, 6):

     ch = 65

     for j in range(i):

        print(chr(ch), end=" ")

        ch += 1

     print()

Output

A

A B

A B C

A B C D

A B C D E


Best Practices

  • Use meaningful variable names like row, column, or number.
  • Keep nested loops simple to improve readability.
  • Use break only when an early exit is required.
  • Use continue carefully so important logic is not skipped.
  • Use pass as a temporary placeholder during development.
  • Choose the correct range() parameters to avoid off-by-one errors.
  • Practice pattern programs regularly to strengthen loop logic.

Frequently Asked Questions (FAQs)

1. What is a while loop in Python?

A while loop repeatedly executes a block of code as long as the specified condition remains True.


2. What is the difference between a for loop and a while loop?

A for loop is used when the number of iterations is known, while a while loop is used when the number of iterations depends on a condition.


3. What does the range() function do?

The range() function generates a sequence of numbers and is commonly used with for loops.


4. What is the break statement?

The break statement immediately terminates the loop and transfers control to the next statement after the loop.


5. What is the continue statement?

The continue statement skips the current iteration and moves to the next iteration of the loop.


6. What is the pass statement?

The pass statement is a placeholder that performs no action. It is used when code is syntactically required but not yet implemented.


7. What are nested loops?

Nested loops are loops placed inside another loop. They are commonly used for pattern printing and matrix operations.


8. Why are pattern programs important?

Pattern programs improve logical thinking and help beginners understand nested loops and loop execution.


9. Can while loops create infinite loops?

Yes. If the loop condition never becomes False, the loop runs forever.


10. Which loop is faster in Python?

Performance differences are usually minimal. Choose the loop that makes your code easier to understand.


Interview Questions and Answers

1. What is a while loop?

Answer:

A while loop repeatedly executes code while a specified condition is True.


2. What is the syntax of a while loop?

Answer

while condition:

    statements


3. What is the purpose of range()?

Answer

It generates a sequence of numbers efficiently for iteration.


4. Explain break with an example.

Answer

The break statement exits the loop immediately.

for i in range(10):

    if i == 5:

        break

    print(i)


5. Explain continue.

Answer

The continue statement skips the current iteration and continues with the next one.


6. Explain pass.

Answer

The pass statement is a placeholder that performs no operation.

if True:

    pass


7. What are nested loops?

Answer

A loop inside another loop is called a nested loop. It is mainly used for matrices and pattern printing.


8. Why are nested loops used?

Answer

They solve two-dimensional problems such as tables, grids, and patterns.


9. What causes an infinite while loop?

Answer

When the loop condition never becomes False or the counter variable is not updated.


10. Difference between break, continue, and pass?

Statement

       Purpose

break

       Stops the loop immediately

continue       

       Skips current iteration

pass

       Does nothing (placeholder)



Comments

Popular posts from this blog

HTML Tag

HTML Input Type Submit Syntax and Example

CSS Text Color Explained with Syntax and HTML Examples