while and if

while

The while keyword starts a loop/repetitive operation, and controls it with a test (like while in NetLogo).  Here's the structure:

while test == True:
    do this
    and this
land here when the test ==False

Examples:

Code
# this will print 1 through 3 on 3 lines
i = 1
while i <= 3:
   print(i)
   i = i+1
print('Done')
Output
1
2
3
Done

 

Code
# add up the numbers from 1 to 10
i = 1
total = 0
while i <= 10:
   total = total+i
   i = i+1
print("Total is ",total)
Output
Total is 55

if, else, elif

4 examples:

if n > 0:
   george = 12
if n > 0:
   harry = "whatever"
else:
   harry = "whatever and a bit"
if n > 0:
   harry = n + 1
elif n < -2:
   harry = n - 1
else:
   harry = 0
if n > 0:
   if harry == "whatever":
      george = 12
   else:
      george = -3
else:
   george =0

 


 

while + if in action

Task: create a function called lcm(a,b) that finds the least common multiple of  the two given numbers, a and b.  This is the smallest number that both a and b divide evenly.  For instance, lcm(3,5) is 15.  The following is an easy, but not necessarily efficient way of doing this...

# keep looking at multiples of a until one of them is divisible by b
def lcm(a,b):

   multiple = a
   while multiple % b > 0:
      multiple = multiple + a
   return multiple
# this is risky, but does the job
def lcm2(a,b):
   multiple = a
   while True:
      if multiple % b == 0:
         return multiple
      multiple = multiple + a
# here's a somewhat more efficient way, by making sure that the multiple is of the larger number...
#   using the function lcm() above as a helper function...
def lcm_better(a,b):
   if a >= b:
      return lcm(a,b)
   else:
      return lcm(b,a)