not decided??
While loop
Even though while
loop is not commonly used in CodeCraft, but since it is so convenient to use CodeCraft visual to view the effect of while
loop, or to check out the difference of while
loop, if
statement and for
loop, why not take advantage of this game as a tool to learn this part of Python knowledge.
While loop syntax:
while some condition evaluated True:
loop body
...
(back to while again)
(break out of the loop until the condition is False)
While-loop header begins with keyword while, then a condition which is a Boolean expression that returns True
or False
and end it with a : (colon), check the example below:
while5
i = 0
while i < 5:
print ( 'i: ', i ) # Indention!! 4 spaces.
i = i+1 # same as i += 1
# back to 'while', check condition again until i=5, break out of the loop
print ('Out of the while block')
...#run...
i: 0
i: 1
i: 2
i: 3
i: 4
Out of the while block
So the steps of a while loop are as follows:
- Check the condition
- Execute the code in the block
- Repeat
Compare for loop and while loop
A for
loop is a loop of a specific length, a while
loop will keep executing the code block under it as long as a Boolean expression is True. A while
statement can have an optional else
clause.
Application in CodeCraft
Function addTo(n), build n columns height from 1 to n, then by the side 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,-10,i,'brick')
sum += i
i += 1
column(n+2,-10,sum,'wool_red')
addTo(5)
See in the pic: The numbers(1,2,3,4,5) are indicated by brick columns, and the red tall column at the far right is the sum of all numbers (1+2+...+5 = 15)
Use more than one conditions in a while loop
# two conditions
i, j = 5, 10
while i<10 and j<50:
i += 1
j += 1
column(i,-10,j,'brick')
# i is from 5 to 10, is x location
j is limited from 10 to 15, it's the column height
In this case, i reach 10 first before j reach 50, so i<10 limit the loop.
Compare while loop and for loop
Factorial calculation
# 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')
# for loop to calculate factorial of n
def for_fact():
n = int(input('Enter an integer>=0: ') )
column(-n, -10, n,'cobblestone')
fact = 1
for i in range (2, n+1):
fact = fact *i # same as fact*=i
column(-n, -12, fact, 'obsidian')
# check the results of two different app in CodeCraft
while_fact()
for_fact()
run and input same number for both application, then from the image you can see they give the same results: brick column is n blocks high, black column is n! blocks high, they mirror each other.
Compare the above while
statement with an if
statement that use the same condition:
Ex. 6.3-2 if5.py
ex. if5.py
i = 0
if i < 5:
print ( 'i: ', i )
i = i + 1
print ('Out of the if block')
...#run...
i: 0
Out of the if block
The code in if5.py
checks the condition only once, but in while5.py
, the code check the condition (which is True the first time), execute the while block and at the end of the while block, the program jumps back to the start of the while statement, checks the condition again 5 times until it's False.
Compare if statement and while loop
When using with the same condition, if
statement and while
loop will behave very differently.
t= int(input("Enter an integer: "))
if t <= 5:
column(t, -21, t, 'brick')
print('brick column height ', t)
t += 1
print('Break out of if block at t=', t, ' yellow column')
column( t, -21, t, 'wool_yellow') # use yellow column to mark the end of if block
s= int(input("Enter an integer: "))
while s <= 5:
column(s+10, -21, s, 'cobblestone')
print('cobblestone column height ', s)
s += 1
print('Break out of while loop at s= ', s, ' yellow column')
column( s+10, -21, s, 'wool_yellow') # use yellow column to mark the end of while block
Enter t
and s
as 2
, from the screenshot of the above examples, you can see very clear that: if
statement test the condition only once, if True
, it continue with all the lines in the if
block(build a column height 2 and t updated to be 3) then get out of the block, so there is only one brick column of height 2 showed up at x = 2, the yellow column (height 3) marks the end of the loop;
while
statement test the condition (True
), go on with the code block (build a column with height 2, update t to t+1) and GO BACK to the beginning, test the condition again..., until t reaches 6, that makes the condition False
, so the code breaks out of the while
loop. In CodeCraft world, columns were built with heights 2,3,4,5, a yellow column (height 6) marks the end of the loop.
(pic)
while loop and if statements work together to control the flow
(Below is a similar project to the last example in previous topic 'Conditionals', while loop and if/else)
Let's look at a project using while
loop and if
statements to decide the flow of control.
j = 0
while j <= 20:
if j <= 5:
column(j, -20, j, 'brick')
elif j <= 10:
column(j, -20, 5, 'brick')
elif j <= 15:
column(j, -20, j, 'brick')
else:
column(j, -20, 10, 'brick')
j += 1
After a while when you are ready to build large buildings, the above app may inspire you to design stairs for the buildings.