almost done

Chapter 6 Loops

Repeated execution of a sequence of statements is called iteration. Loops are used to repeatedly execute blocks of code. Python has two main types of loops: for-loops and while-loops. We also use the break keyword to break out of a loop.

6.1 For-loop:

Is to repeat a block of code a set number of times. The for..in statement is a looping statement which iterates over a sequence of objects i.e. go through each item in a sequence. There are several types of sequences in Python, string, list, turple are the most commonly used. We will see more about sequences in detail in later chapters. What you need to know right now is that a sequence is just an ordered collection of items.

ult step 1.

  • range (3) will give the sequence [0,1,2]. The ending number 3 is not included.
  • range (2, 10) will give the sequence starting from 2 to 9, that is [2,3,4,5,6,7,8,9]
  • range (1, 8, 2) will give the sequence 1 to 7, step 2, that is [1,3,5,7]

Let's generate a number sequence from 0 to 5, then loop through the sequence and print out each number.

Ex. 6.2-1 count5.py

# count5.py
>>> for i in range (6):   
    print i           # Loop body is repeated 6 times
...#run...
0
1
2
3
4
5
>>>

More examples on range( ) Ex. 6.2-2 range_demo.py

>>> for i in range (3, 8):
>>>    print (i)     # Print out 3,4,5,6,7, not including 8.
>>>
>>> for i in range (1, 10, 2):
>>>    print (i)      # print out 1,3,5,7,9
>>>
>>> for i in range (10, 0, -1):
>>>    print (i)      # print out 10,9,8,7,6,5,4,3,2,1

Note that range() generates only one number at a time, if you want the full list of numbers, call list() function on range(), for example, list(range(5)) will result in [0, 1, 2, 3, 4]. Lists are explained more in Chapter 7.

An application of for loop in real life: Suppose you saved $50 already, you earn $2 a day cleaning up the bathroom at home and you spend $5 on snacks per week. How much money you would have at the end of each week?

Ex. 6.2-3 weekly_money.py

# weekly_money.py
>>>saved_money = 50
>>>daily_earning =2
>>>weekly_spend =5
>>>weekly_earning = daily_earning *7
>>>money = saved_money
>>>for week in range (1, 53):
       money=money+weekly_earning-weekly_spend
       print ('Week %d = %d' % (week, money))
>>>
Week 1 = 59
Week 2 = 68
...
Week 52 = 518
>>>

6.3 While-loops

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.

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:

Ex. 6.3-1 while5.py

ex. while5.py

>>> i = 0
>>> while i < 5:                
        print (i)    # Indention!! 4 spaces.
        i = i+1      # increase i by 1, same as i += 1
    print ('Out of the block')
...#run...
0              
1
2
3
4
Out of the block
>>>

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 + 1
   print ('Out of the block')
...#run...
0
Out of the 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.

So the steps of a while loop are as follows:

  • Check the condiction
  • Execute the code in the block
  • Repeat

Use while loop in a function: Ex. 6.3-3 count.py

#count.py                    
>>> def count(number):
        i=1
        while i <= number:
            print i
            i=i+1
>>> count(3)
1
2
3
>>>

We can use more than one conditions with a while loop:

Ex. 6.3-4 two_conditions.py

>>>i, j = 5, 40
>>>while i<10 and j<50:
       i += 1
       j += 1
       print (i, j)
>>>
...#run...
6, 41
7, 42
8, 43
9, 44
10, 45     # Why stop here?
>>>

6.4 Comparing for-loops and while-loops

Note: For-loops are generally easier to use and less error prone than while-loops, although not quite as flexible.

A function to compute the sum from 1 up to number n, using for loop:

Ex. 6.4-1 addTo_for.py

# addTo_for.py
def addTo(n):
    sum=0
    for i in range(1,n+1):
        sum += i
    return  sum

print(addTo(3))
6
print(addTo(100))
5050

Next, let's do the same thing using while loop:

Ex. 6.4-2 addTo_while.py

def addToAgain(n):
    sum = 0
    i = 1
    while i <=n:
        sum += i
        i += 1
    return sum

print(addToAgain(3))
6
print(addToAgain(100))
5050

Calculating factorials

  • Factorial, the product of an integer and all the integers below it; e.g., factorial four ( 4! ) is equal to 432*1=24.
  • The idea of the factorial (in simple terms) is used to compute the number of permutations (combinations) of arranging a set of n numbers. It can be said that an empty set can only be ordered one way, so 0! = 1.

Ex. 6.4-3 for_factorial.py

# for_factorial.py
>>> def for_fact(n):
    n = int ( input ( 'Enter an integer>=0: ') )
    fact = 1
    for i in range (2, n+1):
        fact = fact *i      # same as fact*=i
    print(str (n) + ' factorial is ' + str (fact))
>>> for_fact(n)
Enter an interger: 5
5 factorial is 120

Ex. 6.4-4 while_factorial.py

# while_factorial.py
>>> def while_fact(n):
    n = int(input( 'Enter an integer>=0: '))
    fact = 1
    i=2
    while i <= n:
        fact *= i
        i+=1
    print(str (n) +' factorial is '+ str (fact))
>>> 
>>> while_fact (n)
Enter an interger: 52
52 factorial is 806581751709..................00000000000

A deck of cards can be arranged in 52! ways.

6.5 More Exercises:

Use a function to print out a time table, such as the 8 times table like: 18=8, 28=16...9*8=72.

Ex. 6.5-1 times_table1.py

#  times_table1.py
>>> def times_table1 (num):
    i = 1
    while i <= 9:
        print ( i, ' * ', num, ' = ', i * num)
        # same as print('%d * %d = %d' % (i,num,i*num))
        i + = 1

>>> times_table1 (8)
1 * 8 = 8
2 * 8 = 16
3 * 8 = 24
...
9 * 8 = 72
>>>

Another times table, from 1m, 2m... to n*m.

Ex. 6.5-2 times_table2.py

#  times_table2.py
>>>def times_table2(n, m):    # n, how far
    j = 1
    while j <= n:
        print ('%d * %d = %d' % (j, m, j*m))
        j += 1
>>> times_tables2( 12, 15)       
1*15=15 
2*15=30
...
11*15=165
12*15=180
>>>

In next example, you are going to check the user for his age, if it's an even number, print out even numbers from 2 to the age; otherwise, print out odd numbers from 1 to the age number.

Ex. 6.5-3 evenOdd_toAge.py

# evenOdd_toAge.py
def evenOdd_toAge(age=0):   # Set a default value for age in case the user might fail to provide.
    '''Returns even or odd numbers up to the user's age.

    Age needs to be an integer. If the user's age is even, print out 2 to age number; otherwise, prints out odd numbers.'''

    if age%2 == 0:
        for i in range(2, age+1, 2):
            print ( i )
    else:
        for i in range(1, age+1, 2):
            print ( i )

evenOdd_toAge(10)
2
4
6
8
10
evenOdd_age(7)
1
3
5
7

Check your understanding: What do you think the following code will do?

Ex. 6.5-4 loop_break.py

for n in range(2, 10):
    print ('n is ', n)
    if n< 8:
        print ('The loop ends here.')
        break

# guess first, then check the result:
...#run...
n is 2
The loop ends here.

results matching ""

    No results matching ""