Python Programming

Lecture 3 Iteration

3.1 Iteration: while

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: BMI Calculator v2.0


print("BMI指数计算器\n")
while True:
    try: 
        inp_1 = input('请输入您的体重(kg):\n')
        weight = float(inp_1)
        break 
    except: 
        print('请输入数字')
while True:
    try: 
        inp_2 = input('请输入您的身高(cm):\n')
        height = float(inp_2) 
        break
    except: 
        print('请输入数字')

Example 3: Josephus problem(约瑟夫问题;Hot Potato Game)

  • The Josephus Problem is a classic mathematical puzzle in which $n$ people stand in a circle and every $k$-th person is eliminated in sequence until only one remains. The challenge is to determine the position of the final survivor given $n$ and $k$. It is widely used in computer science to illustrate recursion, circular data structures, and algorithm design.

name_list = ['a', 'b', 'c', 'd', 'e', 'f']
i = 1
while len(name_list) > 1:
    if i % 7 == 0:
        y = name_list.pop()
    else:
        y = name_list.pop()
        name_list.insert(0, y)
        # print(name_list)
    i = i + 1
print(name_list)

Exercise: 存钱达到目标

  • 小明每天存的钱比前一天多 1 元:第一天存 1 元,第二天存 2 元,第三天存 3 元……
  • 请编写程序,让用户输入一个目标金额 $n$,计算:
    1. 第几天存的钱第一次使总金额达到或超过 $n$?
    2. 此时一共存了多少钱?
    3. 提示:先设两个变量,day表示第几天(也是当天存入的金额),total表示当前总金额。

Example 4: Greatest common divisor(最大公约数)


a = int(input('Enter the 1st number:'))
b = int(input('Enter the 2nd 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 5: Prime number (判断质数)



i = int(input("please enter:\n"))
j = 2
while j**2 <= i:
    if i % j == 0: 
        break
    j = j + 1
if j**2 > i: 
    print(i)

Exercise: 根据上面的代码修改,给定一个数,找到这个数的所有因子并把它们放到一个列表里。例如,12的因子有1,2,3,4,6,12。

3.2 Iteration: for

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 refer to the while loop as an indefinite loop because it continues executing until a specific condition becomes False, whereas the for loop iterates over a known set of items, running as many times 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 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

range function

  • The range function generates a sequence of integers.
  • It often used to control the number of iterations in a for loop.
  • 
    for value in range(1,4): 
        print(value)
    
    
    1
    2
    3
    
    
    range(1,6) # 1, 2, 3, 4, 5
    
    range(6) # 0, 1, 2, 3, 4, 5
    
    range(1, 10, 2) # 1, 3, 5, 7, 9
    
    range(10, 1, -2) # 10, 8, 6, 4, 2
    
  • Example 1: generate a list of square numbers
  • 
    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 2: Use for loops to mimic functions

sum()


total = 0
for value in range(1, 101):
    total = value + total  # total+=value
print(total)

len()


a_list = [3, 41, 12, 9, 74, 15]
count = 0
for x in a_list:
    count = count + 1
print(count)

max(), min()


a_list = [3, 41, 12, 9, 74, 15]
largest = a_list[0]
for x in a_list:
    if x > largest :
         largest = x
print(largest)

    sorted(): sorting is a much more complicated and interesting topic.

Exercise: 完美数 (Perfect Number)

  • 编写程序,找出 1 到 100 之间的所有完美数。
  • 定义:一个数如果等于它所有真因子(不包括自身)之和,就叫完美数。
  • 例如:6 = 1 + 2 + 3。6是完美数

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(1,i+1):
        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

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

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

Exercise: 生成棋盘(在下面这段代码基础上修改)


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

1 
2 2 
3 3 3 

1.生成棋盘


* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

2. 加上条件判断


+ * * * *
* + * * *
* * + * *
* * * + *
* * * * +

Summary

  • Iteration
    • Reading: Python for Everybody Chapter 5