Featured Posts

Start Your Journey with Linux Command Line

Image
Start Your Journey with the Linux Command Line: A Comprehensive Guide Whether you are a software developer, system administrator, analytics engineer, or cybersecurity enthusiast, mastering the Linux command line (terminal) is one of the single most effective skills you can acquire. While graphical user interfaces (GUIs) offer visual convenience, the command line interface (CLI) delivers unmatched speed, fine-grained system control, and seamless automation capabilities. Linux Command Line This tutorial breaks down more than 35 core Linux commands into structured, practical modules complete with real-world examples, flags, and command-chaining techniques. By building muscle memory around these fundamentals, you will elevate your daily technical workflow from basic navigation to advanced command orchestration. Why Learn the Command Line? The Linux CLI is not merely a legacy tool—it remains the foundation of modern cloud architecture, server maintenance, DevOps pipelines, and enterp...

Python 3.2.1.14 LAB: Essentials of the while loop

3.2.1.14 LAB: Essentials of the while loop

while loop
Essentials of the While Loop

If you're taking PCAP - Programming Essentials In Python , you may have encountered this question 3.2.1.14 LAB: Essentials of the while loop.

Objectives

Familiarize the student with:

  • using the while loop;
  • finding the proper implementation of verbally defined rules;
  • reflecting real-life situations in computer code.

Scenario

Listen to this story: a boy and his father, a computer programmer, are playing with wooden blocks. They are building a pyramid.

Their pyramid is a bit weird, as it is actually a pyramid-shaped wall - it's flat. The pyramid is stacked according to one simple principle: 

👉 each lower layer contains one block more than the layer above 👈.

The figure illustrates the rule used by the builders:

building blocks
building blocks

Your task is to write a program which reads the number of blocks the builders have, and outputs the height of the pyramid that can be built using these blocks.

Note: the height is measured by the number of fully completed layers - if the builders don't have a sufficient number of blocks and cannot complete the next layer, they finish their work immediately.

Test your code using the data we've provided.

Test Data

Sample input: 6

Expected output: The height of the pyramid: 3

Sample input: 20

Expected output: The height of the pyramid: 5

Sample input: 1000

Expected output: The height of the pyramid: 44

Sample input: 2

Expected output: The height of the pyramid: 1

Solution Code

Solution #1

blocks = int(input("Enter the blocks : "))
height = 0
layers = 1
while layers <= blocks:
    height += 1
    blocks -= layers
    layers += 1
print("The height of the pyramid: ", height)

Solution #2

blocks = int(input("Enter number of blocks: "))
print(f'You can build a pyramid {int(0.5 * ((8 * blocks + 1)**0.5 - 1))} blocks high')
# This is how a pyramid formula is done

Solution #3

blocks = int(input("Enter number of blocks: "))

for n in range(blocks):
    if n*(n+1)/2 <= blocks: # This is how a pyramid formula is done
        height = n

print("The height of the pyramid is:", height)


=================================================================================

Follow the blog to be the first to know ❤

Solving the Pyramid Height with a while Loop

This lab turns a simple real-life story into code you can express with a while loop. A boy and his father build a flat, pyramid-shaped wall where each lower layer contains exactly one more block than the layer above it. Given a number of blocks, the program must output the height of the tallest pyramid that uses only fully completed layers; if there are not enough blocks to finish the next layer, the builders stop immediately. The challenge is finding the right implementation of that verbally defined rule.

The first solution tracks three variables: blocks for the total supply, height for the layers built so far, and layers for the size of the next layer. The loop condition while layers <= blocks checks that enough blocks remain to complete the upcoming layer. Inside the loop, height is increased by one, the required blocks are removed with blocks -= layers, and layers is incremented so the next layer demands one more block. This mirrors the real process: count a completed layer, consume its blocks, and grow the requirement by one.

Understanding the Layered Arithmetic

For six blocks the loops builds layers of 1, 2, and 3 blocks, consuming all six, which yields a height of 3. For twenty blocks the cumulative requirement 1 + 2 + 3 + 4 + 5 equals fifteen, leaving just enough for a fifth layer before the next layer of six exceeds the supply, so the height is 5. The post also shows alternative formulas. One uses the closed-form sum of the first n integers with the expression int(0.5 * ((8 * blocks + 1)**0.5 - 1)), and another tries successive values of n in a for loop to find the largest value where n * (n + 1) / 2 <= blocks. All approaches agree the height is the number of fully completed layers.

Key Takeaways

  • The while loop repeats as long as layers <= blocks, so it stops when the next layer cannot be completed.
  • Each layer uses one more block than the previous layer, so layers increases by one each pass.
  • Subtracting blocks -= layers consumes the blocks spent on the current layer.
  • The height counts only completely finished layers.
  • Sample results: 6 blocks produce height 3, 20 produce 5, 2 produce 1, and 1000 produce 44.
  • A while loop naturally models a process that repeats an unknown number of times.

Frequently Asked Questions

Why must the loop stop before the next layer can be completed?

Because the builders finish immediately when insufficient blocks remain, so the height never counts an incomplete layer.

What happens to leftover blocks?

The remaining blocks are ignored because the pyramid ends after the last fully completed layer.

Why does layers increase each loop?

Because each lower layer contains exactly one more block than the layer above it, so every successive layer demands a larger stack of blocks.

Can the answer also be found with a formula?

Yes. The cumulative sum of the first n integers, n * (n + 1) / 2, is used to find the largest n that fits within the available blocks.

Comments

  1. B=100
    BB=0
    S=0
    while (B>=(S+1)**2):
    S=S+1
    B=B-S**2
    BB=BB+S**2
    print(S,") B=",S**2," | BB=",BB)
    print(S)

    ReplyDelete
  2. Thank you for the solution. Try to test it and match it with the requirements. Also, try to make the variables meaningful so the user can know which refers to what.

    ReplyDelete
  3. Hey thank you for your help. The problem said that the pyramid layers one block greater than the previous but when i put 4 blocks it outputs 2 layers which is a square or rectangle. can you help me?

    ReplyDelete
    Replies
    1. The problem said a pyramid layer, therefore if you insert 4 blocks, only three blocks will be useful to form a pyramid layer which is why you will have a height of two

      Delete
  4. The first solution fail when the input was 1000, the answer was 10.

    ReplyDelete
    Replies
    1. I uploaded a video for each solution and they work just fine. Check the videos and make sure you're writing the exact code. Please let me know in the comments.

      Delete
  5. Great article! I found the information you shared to be insightful and thought-provoking. The examples you provided really helped illustrate your points effectively. I appreciate the effort you put into creating this content and look forward to reading more from you in the future. Keep up the excellent work! if you need homes contact Top-rated Home Builders in Guelph

    ReplyDelete
    Replies
    1. It's amazing to hear this Rachel. You can also keep up with our python lessons on our YouTube Channel here
      https://youtube.com/playlist?list=PLAYx9j051JpluOiHnfHUSTJgm5JUgNSpX

      Delete
  6. I made my way:

    blocks = int(input("Enter the number of blocks: "))

    i = 1
    height = 0
    layers=[]
    if blocks <= 0:
    print("Blocks needs to be > 0")
    else:
    acumulative = 0
    while i <= blocks:
    if (1 in layers) == False and acumulative == 0:
    layers.append(1)
    acumulative = 0
    height = len(layers)
    else:
    acumulative += 1
    if (int(layers[-1]) + 1) == acumulative:
    layers.append((int(layers[-1]) + 1))
    acumulative = 0
    height = len(layers)
    i += 1
    print("The height of the pyramid: ", height)

    ReplyDelete

Post a Comment

Your opinion matters, your voice makes us proud and happy. Your words are our motivation.

Popular Posts

PROJECT MAVEN | The Architecture of Algorithmic Warfare

Data Analysis Roadmap 2026: From Excel Lover to Python-Powered Analyst

Open Source: The Invisible Engine of Your Daily Life

Python for Windows Beginners: Build Your First Automated Workflow in 10 Minutes

Python 4.3.1.10 LAB: Converting fuel consumption