Squares and Patterns

Milada on Flickr

Squares, checkerboards, and hollow boxes… what pattens can you imagine in Python?

You’ve learned how to print triangles in Python — but have you tackled squares? In this article we’ll write some code to display another classic shape in your console, with a twist. Instead of your everyday boring square, we’re going to spice our shapes up with exciting patterns.

SET UP

Open up a browser and navigate to www.repl.it/languages/python3.

On your left you’ll see your editor, where you write your code. On your right is your console, which displays the result of the code.

THE BASIC SQUARE

Before we dive into the exciting stuff, we need to nail the basic square. Imagine your square as a grid with an equal number of rows and columns, where each box contains its own little star.

To output this we’re going to use a nested for loop, which is a fancy way of saying “a for loop inside a for loop”. There are easier ways to print a square — like printing an entire row at once, instead of one star at a time — but the double loop comes in handy for the decoration phase. Let’s start with the inner loop:

for col in range(7):
   print("*", end=" ")
print()

If you run the code by clicking the green “run” button at the top of the Repl.it screen, you’ll see a single row of stars. Essentially, our simple “print” operation is repeated seven times in the loop, one for each column in the first row. In Python, print statements automatically add a “newline character”. Since we want our stars to be next to each other, and not on different lines, we need specify that our end character is a space. We only add the newline character once the entire row is printed!

If we want seven rows, then we need to repeat that whole block of code seven times — using another for loop! Simply pop your three lines of code under a new loop, and you’re good to go.

for row in range(7):
    for col in range(7):
        print("*", end=" ")
    print()

Onto the second task: making our square hollow.

THE HOLLOW SQUARE

In this exercise, you don’t want to print every star in the grid. You only want stars in the first row, last row, first column and last column; otherwise, you print a space. Since we’re adding a condition to our program, we need to add an if statement.

Programming has a couple odd quirks. When you’re counting, for example, you typically start at 0 instead of 1, which means our columns are labelled 0-6 instead of 1-7. The first row is Row 0, and the last row is Row 6.

for row in range(7):
 for col in range (7):
   if col == 0 or col == 6 or row == 0 or row == 6:
     print("*", end=" ")
   else:
     print(" ", end=" ")
 print()

Remember to use the double equals (==) when comparing numbers!

THE CHECKERBOARD

Finally — how can we make a checkerboard?

Building fancier patterns is all about deciding where to print stars and where to print spaces. Technically, you could “hard code” everything, and list the exact row & column number of every star you want to print. This is long, boring, and it’s easy to make mistakes. Plus, if you want to make your square bigger or smaller, you’ll have to edit all that code.

In some situations it’s impossible to avoid hard coding, but in most cases, you can save yourself a headache but thinking up a clever solution. What is the shortest, simplest way to describe the pattern of a checkerboard? Draw a quick sketch and pay attention to the column and row numbers. (And don’t forget to start your labels at zero!)

You might notice that every star in an even row is also in an even column, and every star in an odd row is also in an odd column. In Python, the easier way to check for even / odd numbers is the mod operator.

If the number “n” is even:
n % 2 == 0

And if the number is odd:
n % 2 == 1

So we can write the code for the checkerboard like this:

for row in range(7):
 for col in range (7):
   if (row % 2 == 0 and col % 2 == 0) or (col % 2 == 1 and row %2 == 1):
     print("*", end=" ")
   else:
     print(" ", end=" ")
 print()

CONCLUSION

The types of patterns you can create are limitless! What about a giant ‘X’? Or a diamond pattern? Have fun playing around with your if statements and seeing what pictures you can create. Remember to avoid hard coding wherever possible!

Learn More

hollow rectangle

https://www.geeksforgeeks.org/program-to-print-hollow-rectangle-or-square-star-patterns/

star pyramid patterns

https://codescracker.com/python/program/python-program-print-star-pyramid-patterns.htm

Author

  • Patricia Foster

    Patricia Foster is a computer science student at Carleton University. In addition to working professionally as a software developer, she spends her time reading and writing.

Also In The April 2019 Issue

Use SketchUp to create this fascinating mathematical pattern that appears everywhere in nature.

Learn about the STEAM star’s amazing journey onto Mythbusters Junior and beyond.

What’s the best way to choose a classroom lunch? Or the best way to elect a leader? The answer isn’t so simple.

Keep your passwords at the tip of your fingers, or maybe at the back of your eyes!

Bring your coding skills and your desserts to new levels in this simple Python coding activity.

Learn about the shiny new technology that allows us to be connected like never before.

Squares, checkerboards, and hollow boxes… what pattens can you imagine in Python?

A fun, DIY electronics project that’ll keep you from bumping around in the dark!

Use your favourite block language to animate this fascinatingly odd game.

Can we make a computer using only three simple rules?

How science and tech led to an exciting discovery in one of the most dangerous areas of space.

How did video games become popular before the internet? It’s all about shareware, floppy disks, and human cleverness!

Links from the bottom of all the April 2019 articles, collected in one place for you to print, share, or bookmark.

Interesting stories about science and technology for April 2019.

Interested but not ready to subscribe? Sign-up for our free monthly email newsletter with curated site content and a new issue email announcement that we send every two months.

No, thanks!