Python Programming

Lecture 3 Iteration

3.1 Iteration (1)

1+2+3+...+100=?

The while statement


n = 5
while n > 0:
    print(n)
    n = n - 1
print('Blastoff!')


5
4
3
2
1
Blastoff!
  1. Evaluate the condition, yielding True or False.

  2. If the condition is false, exit the while statement and continue execution at the next statement.

  3. If the condition is true, execute the body and then go back to step 1.

  • This type of flow is called a loop because the third step loops back around to the top.

  • We call each time we execute the body of the loop an iteration.

  • The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates.

  • If the loop repeats forever, it results in an infinite loop.


n = 10
while True:
    print(n)
    n = n - 1
print('Done!')
  • What will happen if you run this?

  • Ctrl+C to terminate it.

  • Finishing iterations with break


while True:
    line = input('Please enter:')
    if line == 'done':
        break
    print(line)
print('Done!')
  • Finishing iterations with continue


while True:
    line = input('Please enter:')
    if line == '#':
        continue
    if line == 'done':
        break
    print(line)
print('Done!')
  • Example 1: Even and Odd

numbers = [12,37,5,42,8,3]
even = []
odd = []
while len(numbers)>0:
    x = numbers.pop()
    if (x%2==0):
        even.append(x)
    else:
        odd.append(x)
print(even)
print(odd)

[8, 42, 12]
[3, 5, 37]
  • Example 2: Greatest common divisor

a = int(input('Enter your first number:'))
b = int(input('Enter your first number:'))
if a >= b:
    x = a
    y = b
else:
    x = b
    y = a
while y!=0:
    r = y
    y = x%y
    x = r
print(x)
  • Least common multiple?

  • Example 3: Finding prime numbers

i = 2
while i < 100:
    j = 2
    while j <= (i/j):
        if not i%j : 
            break
        j = j + 1
    if j > i/j: 
        print(i)
    i = i + 1

Definite loops using for

  • for statement works on the lists.


friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends: 
    print('Happy New Year:', friend)
print('Done!')

Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
  • We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.

  • In particular, friend is the iteration variable for the for loop. The variable friend changes for each iteration of the loop and controls when the for loop completes. The iteration variable steps successively through the three strings stored in the friends variable.

  • The concept of looping is important because it is one of the most common ways a computer automates repetitive tasks.

  • The indentation errors are common.

  • Python uses indentation to determine when one line of code is connected to the line above it. Some languages require the "end" statement.

  • Always indent the line after the for statement in a loop.


friends = ['Joseph', 'Glenn', 'Sally']
for x in friends: 
print('Happy New Year:', x)
print('Done!')

IndentationError: expected an indented block

message = "Hello Python world!"
    print(message)

IndentationError: unexpected indent
  • Forgetting to indent additional lines (logical error)


friends = ['Joseph', 'Glenn', 'Sally']
for x in friends: 
    print('Happy New Year:', x)
print('Looking forward to seeing you,', x)

Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Looking forward to seeing you, Sally

friends = ['Joseph', 'Glenn', 'Sally']
for x in friends: 
    print('Happy New Year:', x)
    print('Looking forward to seeing you,', x)

Happy New Year: Joseph
Looking forward to seeing you, Joseph
Happy New Year: Glenn
Looking forward to seeing you, Glenn
Happy New Year: Sally
Looking forward to seeing you, Sally

3.2 Iteration (2)

  • Now we answer the question. How to calculate 1+2+...+100?

  • First, we need to generate a series of numbers in a list.

  • 
    for value in range(1,5): 
        print(value)
    
    
    1
    2
    3
    4
    
    
    >>> type(range(1,5))
    range
    

>>> numbers = list(range(1,6)) 
#list() creates an empty list.
>>> print(numbers)
[1, 2, 3, 4, 5]

>>> numbers = list(range(6))
>>> print(numbers)
[0, 1, 2, 3, 4, 5]

>>> numbers = list(range(1, 10, 2))
>>> print(numbers)
[1, 3, 5, 7, 9]

>>> numbers = list(range(10, 1, -2))
>>> print(numbers)
[10, 8, 6, 4, 2]
  • 1+2+3+...+100


total=0
for value in range(1,101):
    total=value+total
print(total)
  • Make a list of even numbers


even_numbers = list(range(2,11,2))
print(even_numbers)

[2, 4, 6, 8, 10]

squares = []
for value in range(1,11):
    square = value**2
    squares.append(square)
print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • Example 1: len()


count = 0
for x in [3, 41, 12, 9]:
    count = count + 1
print('Count: ', count)
  • Example 2: sum()


total = 0
for x in [3, 41, 12, 9]:
    total = total + x
print('Total: ', total)
  • Example 3: max(), min()


largest = None
for x in [3, 41, 12, 9, 74, 15]:
    if largest is None or x > largest :
            largest = x
print('Largest:', largest)

Largest: 74
  • Example 4: .reverse()


reverselist = []
count = 0
x = [3, 41, 12, 9, 74, 15]

for itervar in x:
    count = count + 1
for i in range(count-1, -1, -1):
    reverselist.append(x[i])
print(reverselist)

[15, 74, 9, 12, 41, 3]
  • Sorting is a much more complicated and interesting topic.

Nested Loops


x = []
for i in range(1,4):
    x.append([])
    for j in range(1,4):
        x[i-1].append(1)
print(x)

[[1, 1, 1], [1, 1, 1], [1, 1, 1]]

x = []
for i in range(1,4):
    x.append([])
    for j in range(1,i+1):
        x[i-1].append(1)
print(x)

[[1], [1, 1], [1, 1, 1]]

for i in range(1,4):
    for j in range(i):
        print(i,end=" ")
    print()

1 
2 2 
3 3 3  
  • The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

>>> print("hello",end="+")
hello+

for i in range(1,4):
    for j in range(i):
        print(i,end="+")
    print()

1+
2+2+
3+3+3+

3.3 Easy Money Tracker (简易记账本)

Targets:

  • 1. Record the expenses in March
  • 2. Require users to enter expenses one by one
  • 3. Report the total expenses
Step 1: Create a list containing dates


print("简易记账本(三月)")
March=[]
for date in range(20210301,20210332):
    March.append([date])
print()
Step 2: Require Users to enter the date

day=input("请问要输入几号的开销?")
Step 3: Enter the expenses one by one

print("请输入每一笔开销,结束请输入ok")
expense=[]
n=1
while n!=0:
    each = input("第"+str(n)+"笔:")
    if each == "ok":
        n=0
    else: 
        expense.append(float(each))
        n=n+1
    print("记录成功")

March[int(day)-1].append(sum(expense))
Step 4: Calculate the total

expense_total=0
for each_day in March:
    if len(each_day) == 2:
        expense_total = expense_total + each_day[1]

print()
print("本月支出汇总报告")
print("总支出:" + str(expense_total))

Improvement: Multiple days

Improve Step 2: Nested loops

while True:
    day=input("请问要输入几号的开销?如果结束请输入ok: ")
    if day=="ok":
        break
    else:
        # all the programs in Step 3

indentation: select programs, tab (or space)

cancel indentation: select programs, shift + tab

Practice

  • Display the detailed expenses
  • For example, we have entered
    • 3-1, total expenses: 200
    • 3-2, total expenses: 150
    • The output is shown below
    
    3月具体开支信息:
    3-1  100
    3-2  150
    

Summary

  • Iteration
    • Reading: Python for Everybody Chapter 5