Application in CodeCraft
addTo(n)
function
Build n columns with heights from 1 to n, then build a tall column that has height the sum of (1 + 2 + ... + n).
def addTo(n):
sum = 0
i = 1
while i <= n:
column(i, -20, i, 'box_light_blue')
sum += i
i += 1
column(-2, -20, sum,'box_red')
# call the function with input
addTo(5)
In the picture below, the blue columns indicate the values of i
(1, 2, 3, 4, 5) as the computer runs through the while
loop, and the red tall column at the left is the sum of all numbers: 1+2+...+5 = 15.
More than one condition in a while
loop
#two conditions
i, h = 5, 3
while i < 10 and h < 50:
column(i, -20, h, 'box_pink')
i += 1
h += 1
i
(x location) increases from 5
to 9
;h
(the column height) increases from 3
to 7
.
In this case, i
reaches 10 before h
can reach 50, so i < 10
limits the loop.
Factorials
We can use a while
loop to calculate factorials. Do you remember factorials? For example, 4! = 4 * 3 * 2 * 1
# while loop to calculate factorial of n
def while_fact():
n = int(input( 'Enter an integer >= 0: '))
fact = 1
i=2
while i <= n:
fact *= i
i += 1
column(n, -10, n, 'brick')
column(n, -12, fact, 'obsidian')
# call the function
while_fact() # enter n as 4
We can also use a for
loop to calculate factorials:
# for loop to calculate factorial of n
def for_fact():
n = int(input('Enter an integer >= 0: '))
column(-n, -10, n, 'brick')
fact = 1
for i in range (2, n+1):
fact *= i # same as fact = fact *i
column(-n, -12, fact, 'obsidian')
# call the function
for_fact() # enter n as 4
Run and input the same number for both applications. In this image, you can see that they give the same results: the brick column is n blocks high, and the black column is n! blocks high.