暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python基础-3 流程控制

一只大鸽子 2022-05-16
1000

流程控制即控制代码执行的顺序。Python中的流程控制一般通过判断、循环语句实现。

本文思维导图:


一、判断

1.1 if语句

最常用的判断语句是if语句:

例:if语句

    x = int(input("Please enter an integer: "))


    if x < 0:
    x = 0
    print('Negative changed to zero')
    elif x == 0:
    print('Zero')
    elif x == 1:
    print('Single')
    else:
    print('More')

    注1:这里if下面的语句有4个空格缩进,说明下面的两行语句是属于if语句的。Python中用缩进表示代码所属级别。

    注2:elif即对else if的缩写。



    用户输入一个整数存到变量x中,然后对x进行判断。

    如果x小于0,就让给x赋值0,并且使用print输出消息Negative changed to zero;否则,如果x等于0,就输出消息Zero;否则,如果x等于1,输出消息Single;否则,以上都不符合,输出消息More

    if语法:

      if 条件:
      命令1
      elif 条件:
      命令2
      ...可以有更多elif...
      else:
      命令n





      二、循环

      2.1 for语句

      Python中最常用的循环是for语句。典型用法是用for来遍历一个列表(或任意可迭代对象)

      例:使用for语句打印words中单词及其长度。

        words = ['cat', 'window', 'defenestrate']
        for w in words:
        print(w, len(w))

        for -in语法:

          for x in 可迭代对象:
          语句

          2.2 遍历集合

          遍历集合时修改集合的内容,会很容易生成错误的结果。因此不能直接进行循环,而是应遍历该集合的副本或创建新的集合:

            #创建一个集合。集合就是一些“键:值”形式的键值对。
            users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}


            # 在副本上迭代
            for user, status in users.copy().items():
            if status == 'inactive':
            del users[user]


            # 或者创建新集合
            active_users = {}
            for user, status in users.items():
            if status == 'active':
            active_users[user] = status

            2.3 range()函数

            range可当成是一种不可变序列。 range
            (startstop[step]),range可以传入三个参数,起始值,终止值,步长。其中,start默认值为0,步长默认为1。

            range的典型用法就是只指定stop,用于循环指定次数。

              for i in range(5):
              print(i)

              range(5)就能循环5次:

                0
                1
                2
                3
                4

                range()三参数形式startstop[step]

                  list(range(0, 10, 3)) #[0, 3, 6, 9]


                  使用len()和range()可以按索引迭代序列(不推荐)。

                    a = ['Mary', 'had', 'a', 'little', 'lamb']
                    for i in range(len(a)):
                    print(i, a[i])

                    推荐使用更简洁的enumerate

                      a = ['Mary', 'had', 'a', 'little', 'lamb']
                      for i,x in enumerate(a):
                      print(i,x)



                      2.4 while循环

                      while循环用于在某些条件下进行循环,条件为假时,循环结束:

                        a, b = 0, 1
                        while a < 10:
                        print(a)
                        a, b = b, a+b


                        while语法:

                          while 条件为真:
                          执行...


                          2.5 循环中的break,continue语句

                          break
                           
                          语句和 C 中的类似,用于跳出最近的 for
                           或 while
                           循环。

                          continue
                           
                          语句也借鉴自 C 语言,表示继续执行循环的下一次迭代。

                            for i in range(1, 100):
                            if i % 7 == 0 and i % 5 == 0:
                            print(i)
                            print(i, " is good")

                            使用break,会直接跳出所在的for循环

                              #例子break。
                              for i in range(1,100):
                              if i % 7 == 0 and i % 5 == 0:
                              print(i)
                              break #会结束所在的for循环
                              print(i, " is good")

                              使用continute会跳过下面的语句,继续下一次循环。

                                # continue例子
                                for i in range(1, 100):
                                if i % 7 == 0 and i % 5 == 0:
                                print(i)
                                continue
                                print(i, " is good") #会被跳过

                                2.6 for-else语法(不推荐)

                                循环结束时执行else,break停止循环时不执行。

                                  # for- else


                                  for i in range(5):
                                  if i**1 +i**2 + i**3 > 200:
                                  print("find ",i)
                                  break
                                  else:
                                  print("not find")


                                  #not find

                                   循环结束,没有break,就执行else子句。

                                    # for- else




                                    for i in range(10):
                                    if i**1 +i**2 + i**3 > 200:
                                    print("find ",i)
                                    break
                                    else:
                                    print("not find")


                                    #find 6

                                     循环被break提前结束,不执行else子句。


                                    三、其它

                                    3.1 pass语句

                                    pass语句什么都不做,通常当做占位符。

                                    比如我们预期将来要写一个函数,可以先使用pass占位,后面再实现实际功能。

                                      def initlog(*args):
                                      pass # Remember to implement this!

                                      3.2 match

                                      match语句是Python3.10新特性,用来匹配目标。


                                        def http_error(status):
                                        match status:
                                        case 400:
                                        return "Bad request"
                                        case 404:
                                        return "Not found"
                                        case 418:
                                        return "I'm a teapot"
                                        case _:
                                        return "Something's wrong with the internet"

                                        变量名” _
                                         被作为 通配符 并必定会匹配成功

                                        除了字面值,match还可以匹配模式。

                                          # point is an (x, y) tuple
                                          match point:
                                          case (0, 0):
                                          print("Origin")
                                          case (0, y):
                                          print(f"Y={y}")
                                          case (x, 0):
                                          print(f"X={x}")
                                          case (x, y):
                                          print(f"X={x}, Y={y}")
                                          case _:
                                          raise ValueError("Not a point")

                                          类形式:

                                            class Point:
                                            x: int
                                            y: int


                                            def where_is(point):
                                            match point:
                                            case Point(x=0, y=0):
                                            print("Origin")
                                            case Point(x=0, y=y):
                                            print(f"Y={y}")
                                            case Point(x=x, y=0):
                                            print(f"X={x}")
                                            case Point():
                                            print("Somewhere else")
                                            case _:
                                            print("Not a point")


                                            文章转载自一只大鸽子,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                                            评论