Python is a very handy tool to do simple arithmetic for us. We can write simple programs to search through numbers for those that have specific properties. For instance, let us suppose we wish to find all the numbered squares from 1 to 100. In other words, we wish to find numbers in the range [1,100] that are squares of other numbers.

One way to do it is to realize that 1 squared is 1 and 10 squared is 100, so the square numbers we are looking for are simply squares of numbers from 1 to 10. Here is a simple Python program to do the task for us:

In this program we create a for loop that cycles through 10 values (the argument of the range function). Typically a for loop begins from 0 to one less than the range’s argument, i.e., from 0 to 9 in our case. So we add 1(i+1) so that the loop really goes from 1 to 10. Inside the for loop we print the square of this number in a pretty format.

The output is:

The same program could also have been written as:

Note that the range now begins with 1 and will end at 10 because the second argument to the range function is 11, which is one more than what we need. The output will be the same as before:

A second way to find numbered squares from 1 to 100 is to cycle through all numbers from 1 to 100 checking if each is a square. Here is how that would work:

Here we cycle through the numbers from 1 to 100. At each step we find its square root using the exponentiation operator. Note that the square root need not be an integer (e.g., the square root of 2 is an irrational number that goes 1.414.2135..) We convert this to an integer using the int() function. Then we ask if that integer squared (i.e., s squared) gives us back the original number (i.e., i). If so, then we can be sure we have hit upon a square. The output will be:

Thus we have a very handy Python approach to find numbered squares for us in a given range. Experiment with it by changing the range and finding higher square numbers! Or to make things more interesting, use it to find numbered cubes!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.