在流程控制语句中,只有for语句不需要在语句外面声明变量

  1. for i in range(5): # i未在for语句外面申明就使用,没有报错
  2. print(i)
  3. while i<10: # 此时会报错,因为i未声明,需要在while循环外面先申明再使用
  4. print(i)

1. if else条件语句

Python 中的 if else 语句可以细分为三种形式,分别是 if 语句、if else 语句、 if elif else 语句。

  1. a=10
  2. b=6
  3. if a>b:
  4. r=a
  5. else:
  6. r=b
  7. 简化: r = a if a>b else b
  8. # if elif else语句
  9. def func(i):
  10. if i == 3:
  11. print(3)
  12. elif i == 4:
  13. print(4)
  14. elif i == 5:
  15. print(
  16. else:
  17. print(6)

3. while循环

while循环是通过一个条件来控制是否要继续反复执行循环体中的语句。

  1. while 条件表达式:
  2. 条件成立重复执行的代码
  3. ——————————————————————————————————————————
  4. while 条件表达式:
  5. 条件成立重复执行的代码
  6. else:
  7. 循环正常结束后要执行的代码
  1. i=int(input("请输入:"))
  2. while i<4:
  3. print(i)
  4. break
  5. else:
  6. print("输入过大")
  1. 如果在while循环中执行了break终止了循环导致非正常结束,else后面的语句不会执行;只执行了continue,else后面的语句是会执行的
  2. while语句,表达式的变量需要在外面先创建好再使用。

4. for循环

python中的for循环与java,c中的for循环不同,没有迭代停止条件,只是将序列中的元素按顺序遍历。

  1. for 临时变量 in 序列:
  2. 重复执行的代码
  3. else:
  4. 循环正常结束后要执行的代码
  5. words = ['A','B','C','D']
  6. for i in words:
  7. print(i,ending="")
  8. >>> ABCD

4.1 for语句 + range()

for语句结合range()函数可以实现java的for循环遍历功能
**range()**是range类的实例对象。
**range(start,stop[,step])**——>从start(包括)到stop(不包括)的整数序列。默认从0开始,step默认为1。

  1. for i in range(0,3,1):
  2. print(i)
  3. >>> 0,1,2

4.2 for + enumerate()

  1. lists=["你好","我好","大家好"]
  2. dict={}
  3. for index,value in enumerate(lists):
  4. dict[value]=index
  5. dict={"你好":0,"我好":1,"大家好":2}

5. else循环子句

**else**循环子句在for迭代完或者**while**终止时执行。但是假如循环被**break**语句终止则不执行**else**语句。

  1. for n in range(2,10):
  2. for x in range(2,n):
  3. if n%x ==0:
  4. print(n,"等于",x,"*",n//x)
  5. break
  6. else:
  7. print(n,"是一个素数")
  8. while True:
  9. i=int(input("请输入:"))
  10. while i < 4:
  11. print("输入正确")
  12. break
  13. else:
  14. print("输入数字过大")
  15. continue

6. break,continue和pass语句

  • break语句可以终止当前的一层循环,包括while和for在内的所有控制语句
  • continue语句的作用没有break语句强大,它只能中止本次循环而提前进入下一次循环中。
  • pass语句表示空语句。它不做任何事情,一般起到占位作用。

    7. match语句

    **python 3.10**添加上的特性

    6. assert断言

    可以看做是功能缩小版的 if 语句,它用于判断某个表达式的值,如果值为真,则程序可以继续往下执行;反之,Python 解释器会报 AssertionError 错误。
    assert 语句的语法结构为:assert 表达式
    1. mathmark = int(input())
    2. #断言数学考试分数是否位于正常范围内
    3. assert 0 <= mathmark <= 100
    4. #只有当 mathmark 位于 [0,100]范围内,程序才会继续执行
    5. print("数学考试分数为:",mathmark)