Starting from:

$30

ITI 1120 Lab # 6

ITI    1120
Lab    #    6
while loops, lists …
1
Star/ng    Lab    6    
• Open    a    browser    and    log    into    Blackboard    Learn    
• On    the    le?    hand    side    under    Labs    tab,    find    lab6    material    
contained    in    lab6-students.zip    file    
• Download    that    file    to    the    Desktop    and    unzip    it.
2
Before    star/ng,    always    make    sure    
you    are    running    Python    3    
This    slide    is    applicable    to    all    labs,    exercises,    assignments    …    etc        
ALWAYS    MAKE    SURE    FIRST    that    you    are    running    Python    3.4    (3.5 is    
fine    too)    
That    is,    when    you    click    on    IDLE    (or    start    python    any    other    way)    
look    at    the    first    line    that    the    Python    shell    displays.    It    should    say    
Python    3.4    or    3.5        (and    then    some    extra    digits)    
If    you    do    not    know    how    to    do    this,    read    the    material    provided    
with    Lab    1.    It    explains    it    step    by    step    
3
4
Later    on    if    you    wish,    you    can    type    them    
into    a    computer    (or    copy/paste    from    the    
solu/ons    once    I    poste    them)    
Do    all    the    exercises    labeled    as    
Task    in    your    head    i.e.    on    a    
paper    
Task    1        
Go to the page below in your interactive textbook
- read through
- click Forward until reaching the end on the Python Visualizing
example (to understand it)
- and answer the two questions and the end:
http://interactivepython.org/runestone/static/thinkcspy/MoreAboutIteration/ThewhileStatement.html
A    solu/on    with    for    loop    
def sum_odd_for(n):
 odd_sum = 0
 for num in range(n):
 if num % 2 == 1:
 odd_sum = odd_sum + num
 return odd_sum
6
def sum_odd_while(n):
 odd_sum = 0
 i=1
 while i < n:
 if i % 2 == 1:
 odd_sum = odd_sum + i
 i=i+1
 return odd_sum
def sum_list_for(a):
 ''' (list)->num '''
 list_sum = 0
 for i in range(len(a)):
 if a[i] % 2 == 1:
 list_sum = list_sum +a[i]
 return list_sum
A    solu/on    with    a    while    loop
Study    of    while vs for    …    in    some    elementary    func/ons:    
A    solu/on    with    for    loop     A    solu/on    with    a    while    loop
Problem: sum of positive odd integers smaller than n
Problem: Sum of odd numbers in a given list a
def sum_list_while(a):
 ''' (list)->num
 list_sum = 0
 i=0
 while i < len(a):
 if a[i] % 2 == 1:
 list_sum = list_sum + a[i]
 i=i+1
 return list_sum
7
def minimum_for_v2(a):
 ''' (list)->num '''
 minimum = a[0]
 for i in range(len(a)):
 if a[i] < minimum:
 minimum = a[i]
 return minimum
Study    of    while vs for    …    in    another    important        elementary    func/ons:    
Two        solu/ons    with    for    loop        
(over    elements    and    over    indices) A    solu/on    with    a    while    loop
Problem:
find a minimum element in a list (of length at least 1)
def minimum_while(a):
 ''' (list)->num'''
 minimum = a[0]
 i=0
 while i < len(a):
 if a[i] < minimum:
 minimum = a[i]
 i=i+1
 return minimum
def minimum_for_v1(a):
 ''' (list)->num '''
 minimum = a[0]
 for element in a:
 if element < minimum:
 minimum = element
 return minimum
8
Task    2    and    Programming    Exercise    1
After studying the previous four functions
1. Open the file called seven_functions.py Copy/paste, one by
one, the three solutions labeled with “# with while loop”
into Python visualizer. Run through each example and
understand how the solutions work and how the variables
change in the loops. Play by changing what variable i is
initialized to and how it is incremented (do for example i=i
+3) and see what happens. As always, you can find python
visualizer here (make sure you choose Python 3)
http://www.pythontutor.com/visualize.html#mode=edit
2. Programming exercise 1: Open file called prog-ex-1.py
Complete there the function sum_odd_while_v2 that takes an
integer n as input and computes the sum of all odd integers
between 5 and n. Use WHILE LOOP only and NO IF STATEMENT.
>>> sum_odd_while_v2(10)
21
>>> sum_odd_while_v2(-7)
0
Programming    Exercise    2        
(Here    is    a    problem    that    in    Python    CANNOT    be    solved    with    FOR    LOOP)    
Write a program that
• asks the user for two integers (one by one
or at the same time if you know how to
handle it). Then it adds them and displays
the sum.
Then the user is asked to enter ‘yes’ if she
wishes to perform the operation again, and
otherwise if she enters anything other than
‘yes’ the program terminates. The operation
(the bullet above) is repeated, as long as
the user enters ‘yes’.
Task    3        
Ques'on    1.    What    does    the    program    below    print    if    the    input    user    entered    was:    
1 5        -3        0
Ques'on    2.    Can    you    tell    what    the    program    does?    Write    one    sentence    
explaining    it    in    plane    English.    
        
Task    4        
Ques'on    1.        How many times does
the code on the right print aha?
Task    5        
Ques'on    1.        What does the
the code on the write
print?
ps. sometimes I say code,
sometimes I say program.
I mean the same thing.
Programming    Exercise    3        
Write    a    func/on    first_neg    that    takes    a    (possibly    empty)        list    of    
numbers    as    input,    finds    the    first    occurrence    of    a    nega/ve    
number,    and    returns    its    index    (i.e.    posi/on        in    the    list)    of    that    
number.    If    there    is    no    nega/ve    number    or    the    list    is    empty,    the    
program    should    return    None.    Use    while    loop    (and    not    for    loop)    
and    and    your    while    loop    should    stop    looping    once    the    first    
nega/ve    number    is    found.        
Test    your    func/on    with    at    least    the    examples    below    

>>> first_neg([2, 3, -1, 4, -2])
2
>>> first_neg([2, 3, 1, 4, 2])
>>> first_neg([])
Programming    Exercise    4            
Write    a    func/on    sum_5_consecu/ve    that    takes    a    list    of    numbers    as    input    and    
returns    True    if    there    are    5    consecu/ve    numbers    in    the    list    that    sum    to    zero.    
Otherwise    it    returns    False.    You    may    assume    that    the    list    has    at    least    5    
elements        
Solve    this    in    two    ways:        
1. for    loop    (over    indices    of    the    list)    
2. while    loop    (over    indices    of    the    list)    
In    both    cases    need    to    think    about    “stopping    condi/on”    in    order    to    avoid    
“IndexError: list index out of range”    
3.    Test    your    func/on    with    at    least    the    examples    below
>>> sum_5_consecutive([2, 3, -3, 2, 4,-6])
True
>>> sum_5_consecutive ([-10, 1, 1, 4, 2, 10, 13])
False
>>> sum_5_consecutive([2, 1, -3, -3, -3, 2, 7, 4, -6])
True
>>> sum_5_consecutive ([])
False
>>> sum_5_consecutive ([1, -1,0])
False
Programming    Exercise    5    :    
Different    ways    to    create    useful    lists     Recall, for example, that
a=[2] creates a list (refer to by variable a) with one element, a number
2 in this case
b=[None] creates a list of length 1, but where, for now, we do not want
to specify a value so we might as well put None
c=[] creates an empty list of length zero
Recall further that multiplying a list by an integer n, creates a new
list that repeats the given list n times. Or that “adding” two lists
creates a new lists that concatinates the given two lists.
For example
[7,2]*3 creates a list [7,2,7,2,7,2]
[1,2]+[10,20,0] creates a list [1,2,10,20,0]
Finally recall the slicing … for example, if a=[2,3,4,1], a[:] returns
the new list with the same elements as a.
Open    the    file    called    crea/ng_various_lists.py.    The    first    line    is    given    to    you.    It    asks    the    user    to    enter    a    posi/ve        
even    integer    n.    Those    bullets    that    are    green    below,    try    to    find    at    least    two    solu/ons:    one    using    eg.    
mul/plica/on    and    another    using    a    loop    with    accumulator    pafern.        
1. Create    a    list    a    (i.e refered    to    by    variable    a)    of    length    n    filled    with    zeros    
2. Create    a    list    b    of    length    n    filled    with    random    numbers    between    1    and    100    
3. Create    a        variable    c    that    is    an    alias    of    b    
4. Set    first    half    of    the    elements    of    c    to    zero,    and    then    print    both    b    and    c    
5. Copy    list    b    into    a    list    d    
6. Create    a    new    list    e    that    has    every    2nd    element    of    b    
Programming    Exercise    6:    Fibonacci    Numbers    
Write    a    func/on    called    fib(n)    that    takes    as    input    an    integer    n    (greater    
than    1)    and    creates    a    list    containing    n    values    such    that    
                    a[0]    =    1    
                    a[1]    =    1    
                    a[i]    =    a[i-1]    +    a[i-2] for    all    i    in    the    range    1    <    i    <    n    
and    it    prints    that    list    once    it    creates    it    
>>> fib(7)
[1 1 2 3 5 8 13]
Once    you    are    done,    trace    your    program    on    paper    and    then    Python    
visualizer    to    see    what    the    values    in    the    list    will    be    for    n=5.    
Programming    Exercise    7:        
Write    a    func/on    inner_product    that    that    takes    as    input    two    lists    (of    
same    length)    of    integers    and    then    computes    and    returns    the    inner    
product    of    the    two    lists    of    integers.    The    inner    product    of        
two    lists    x    =    [x1,    x2,    ...,    xn]    and    y    =    [y1,    y2,    ...,    yn]    is    the    value        
x1    y1    +        x2    y2        +        ...        +        xn yn    .
>>> inner_product([2,3,4], [1,0,2])
10
More    programming    Exercises:    
Do    everything    in    the    first    13    exercises    here    
http://interactivepython.org/courselib/static/thinkcspy/Lists/
Exercises.html
********    
and    if    you    need    more    exercises    ….    
go    to    the    web    site    below,    for    some    more    prac/ce    programming    ques/ons    but    be    
aware    that    the    web    site    is    in    Python    2,    thus    if    you    do    these    exercises    do    them    on        
your    own    computer    AND    NOT    in    the    lifle    browser    window    of    the    web    site.    
http://codingbat.com/python