# 分支结构

Python程序正常是从上往下按顺序执行,当需要选择是否执行某代码块的时候,这个时候就需要分支语句。

num1 = input("input a number:")
num1 = int(num1)

if num1 < 20 :
    print("lower than 20")
else:
    print("equal or bigger than 20")

num1 = input("input a number again:")
num1 = int(num1)

if num1 > 80:
    print("bigger than 80")
elif num1 > 65:
    print("bigger than 65")
else :
    print("lower or equal 65")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

下面是常见的错误:

# 同一个代码块的需要保持相同的缩进,否则会出错
num1 = input("input a number:")
num1 = int(num1)

if num1 < 20 :
    print("lower than 20")
      print(" < 20")

# 遗忘冒号
if num1 < 20
    print("lower than 20")
1
2
3
4
5
6
7
8
9
10
11

if条件中,除了False外,还有这些None,0,"",(),[],{}会被当作False来处理:

str1=""
if str1 == False:
    print("It is false")

if str1:
    print("It is true")
else:
    print("It is not true")
1
2
3
4
5
6
7
8

当时用多重elif时,要把覆盖范围小的写在前面:

num1 = input("input a age:")
num1 = int(num1)

if num1 >= 60:
    print("这是老年")
elif num1 >= 40:
    print("这是中年")
elif num1 >= 18:
    print("这是青年")
elif num1 >= 0:
    print("这是少年")
else:
    print("不正常的年龄!")
1
2
3
4
5
6
7
8
9
10
11
12
13

上面的条件如果颠倒,改成从下往上是不对的。

在条件中如果暂时不想写条件体可以使用pass语句,这样不会有语法错误也能跳过当前条件了:

if {}==False:
    pass
else:
    print("not null")
1
2
3
4

# 断言

断言多用于软件测试,它用于对一个bool表达式进行断言,如果表达式为True,则继续执行,否则会引发AssertionError,比如下面,当输入35时,就会引发错误。

num1 = input("input a age:")
num1 = int(num1)

if 100 > num1 >= 60:
    print("这是老年")
else:
    assert num1 < 30
    print("num1 is lower than 30")
1
2
3
4
5
6
7
8

# 循环

循环语句可以在满足循环条件的情况下反复多次执行一段代码,这些重复执行的代码被称为循环体。一个完整的循环一般包括:初始化语句,循环条件,循环体,迭代语句。

# while循环

list1 = list(range(1,10,1))
i=0
while i<len(list1):
    print(list1[i])
    i+=1
else:
    print("beyond the list,last element:%s" % i)
1
2
3
4
5
6
7

# for循环

# 遍历字符串
for i in "hello":
    print(i)

# 遍历range
for i in range(1,10,2):
    print(i)

# 遍历列表
sum=0
list1 = [1.0,2,3,4.0]
for i in list1:
    if isinstance(i,int):
        sum += i
print(sum)

# 遍历字典
dict1={"math":100,"english":80,"chinese":90}
for key,value in dict1.items():
    print(key,value)

for key in dict1.keys():
    print(key,dict1[key])

# for 的 else用法:
for i in range(1,5):
    print(i)
else:
    print("last element %s" % i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# 嵌套循环

for i in range(1,10):
    for j in range(1,i+1):
        print("%s * %s = %s" % (j,i,i*j),end="  ")
    print()
1
2
3
4

# for表达式

for表达式利用range,元组,列表等可迭代对象创建新的列表,它与普通for循环不同的是它把循环体的表达式放在了for前面。

list1 = [x*x for x in range(1,10)]
print(list1)
print(type(list1))
list2 = [x*x for x in range(1,10) if x % 2==0]
print(list2)
# 生成器
generator = (x*x for x in range(1,10))
print(generator)
for i in generator:
    print(i)

list3 = [(y,x) for x in range(1,10) for y in range(1,x+1)]
print(list3)

list4=[10,22,30,43,52]
list5=[2,3,4]
print([(x,y) for x in list4 for y in list5 if x % y ==0])

print({num:num*2 for num in list1})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 常用的函数

abc = ["a","b","c"]
num = [1,2,3]
print([x for x in zip(abc,num)])

num2=[4,5]
list2 =[x for x in zip(reversed(abc),num2)]
print(list2)

list3 = [x for x in sorted(list2)]
print(list3)
1
2
3
4
5
6
7
8
9
10

# 控制循环结构

在循环体中想跳过本层循环使用continue,想结束循环使用break;

for i in range(1,10):
    if i % 2 == 0:
        continue
    print(i)
    if i == 7 :
        break
else:
    print("for loop end!")
1
2
3
4
5
6
7
8

# 应用

输入为4时,输出:


01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07

1
2
3
4
5
6

当输入为5时,输出:


01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09

1
2
3
4
5
6
7

解:

n = input("请输入一个正数:")
n = int(n)
dict1 = {}
for i in range(n):
    dict1[i]=[]
    for j in range(n):
        dict1[i].append(None)

print(dict1)

row=0
col=0
i=1
while True:
    #向下
    print("向下")
    while(True):
        print("row: %s ,col: %s,value:%s" % (row,col,i))
        dict1[row][col]=i
        i+=1
        if row == n-1 or dict1[row+1][col]!=None:
            col+=1
            break
        if dict1[row+1][col]==None:
            row+=1

    if i > n*n: break
    #向右
    print("向右")
    while(True):
        print("row: %s ,col: %s,value:%s" % (row,col,i))
        dict1[row][col]=i
        i+=1
        if col == n-1 or dict1[row][col+1]!=None:
            row-=1
            break

        if dict1[row][col+1]==None:
            col+=1

    if i > n*n: break
    #向上
    print("向上")
    while(True):
        print("row: %s ,col: %s,value:%s" % (row,col,i))
        dict1[row][col]=i
        i+=1
        if row == 0 or dict1[row-1][col]!=None:
            col-=1
            break
        if dict1[row-1][col]==None:
            row-=1
    if i > n*n: break

    #向左
    print("向左")
    while(True):
        print("row: %s ,col: %s,value:%s" % (row,col,i))
        dict1[row][col]=i
        i+=1
        if col == 0 or dict1[row][col-1]!=None:
            row+=1
            break

        if dict1[row][col-1]==None:
            col-=1
    if i > n*n: break

displayNum=0
finalNum = n * n
while finalNum > 0:
    displayNum+=1
    finalNum //=10


for i in range(n):
    for j in range(n):
        print("%0{0}i".format(displayNum) % dict1[i][j],end=" ")
    print()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79