On this page click on the code samples to execute them.
The for loop combined with the range function is the most direct approach:
for i in range(1, 6):
print(i**2)
It is also possible to combine a while loop with the incrementation of a variable at each iteration of the loop:
i = 1
while i <= 5:
print(i**2)
i = i + 1
The order of the values can be reversed by using a decrementation:
i = 5
while i > 0:
print(i**2)
i = i - 1
Summing the odd integers with a while loop reaches the same result without using the ** operator:
i = 1
n = 1
while i < 10:
print(n)
i = i + 2
n = n + i
A recursive function is another approach which has a certain similarity with the while loop:
def f(i, n):
if i < 10:
print(n)
f(i + 2, n + i + 2)
f(1, 1)
Using the functional programming approach a solution in one line is possible:
list(map(lambda i: print((i+1)**2), range(5)))
The previous approaches have the merit of a certain generality which the following solution lacks:
print(1) print(4) print(9) print(16) print(25)
The results can be put in a CSV file and then displayed in a spreadsheet and a bar chart:
# Create a CSV file containing the squares.
with open('squares.csv', 'w') as f:
f.write('N,N**2\n')
for i in range(1, 6):
f.write(str(i) + ',' + str(i**2) + '\n')
# Display it as a spreadsheet.
show_file('squares.csv')
# Display it as a bar chart.
chart(read_file('squares.csv'), mark='bar', x_type='ordinal')
The results could also be drawn using the turtle metaphor:
# This program uses the turtle to draw the
# numbers using 7 segments.
from turtle import hop, lt, rt, fd, pensize
dist = 20 # length of each segment
segments = { # the 7 segments of each symbol
' ':0,
'0':63, '1':12, '2':118, '3':94, '4':77,
'5':91, '6':123, '7':14, '8':127, '9':95
}
def print_char(c): # draw a symbol
lt(90)
hop(); fd(dist)
bits = segments[c] # each bit = 1 segment
for i in range(7):
if (bits & 1) == 0: hop()
fd(dist)
bits >>= 1
if i != 2: rt(90)
hop(); fd(dist)
lt(90)
hop(); fd(dist/2)
def print(n): # print a number
for c in str(n):
print_char(c)
print_char(' ')
hop(); fd(-175); pensize(5)
for i in range(1, 6): # compute the squares
print(i**2)