Python中流程控制

流程控制

if判断

  •     if判断的基本语法为:

        if 条件:

            缩进的代码块

        例:设有a = 10 , b = 20

           if a < b:

                print(b)

  •           if...else 用法:

          if 条件:

              缩进的代码块

          else:

              缩进的代码块

         例:设有a = 10 , b = 20

            if a > b:

                print(a)

            else:

                print(b)

  •     多重判断用法

        if 条件:

            缩进的代码块

        elif 条件:

            缩进的代码块

        elif 条件:

            缩进的代码块

        else:

            缩进的代码块

        例:输入一个学生的分数,90以上为A,80到90之间为B,60到80之间为C,60以下为D

            score = int(input("puts  your score: "))

            if score >= 90:

                print("A")

            elif score >=80:   #由于不满足score > 90才会跳到这里进行判断,所以无需写成“ elif 90>score>=80:”下同。

                print("B")

            elif score >=60:

                print("C")

            else:

                print("D")

流程控制之while循环

  •     基本语法

        while 条件:

            循环体

        如果条件为真,则执行循环体,执行完毕后再次判断循环条件是否执行下一次循环,依此类推。

            例:循环打印从1到10

        i = 1

        while i <= 10:

            print(i)

            i += 1

            例:循环打印1到10之间的奇数

            i = 0 

            while i < 10:

                if i %2 == 1:

                    print(i)

                i += 1

  •     死循环

            while True:

                print("----------------")

  •     break 与 continue

    break 是直接跳出循环,continue是跳过本次循环继续下一次循环

            例:打印1到10,若到8则终止打印

            i = 1

            while i <= 10:

                if i == 8:

                    break

                print(i)

                i += 1

            例:打印1到10,若到8则跳过8继续打印其他数字

            i = 1

            while i <= 10:

                if i == 8:

                    i += 1

                    continue

                print(i)

                i += 1

  •     while嵌套

            例:使用while循环打印九九乘法表

                i = 0

                while i < 9:

                    j = 0

                    i += 1

                    while j < i:

                            j += 1

                            print("%s*%s=%s" %(j, i, i * j), end=' ')  #end='  '的作用就是打印完这一行不换行  

                    print()#打印换行

 
 

流程控制之for循环

  •     迭代式循环:for,语法如下

        for i in range(10)

                缩进的代码块

         例:循环打印1到10的所有整数

            for i in range(1,10):

                print(i)

  • break和continue用法同while循环一样
  • 循环嵌套

    例:打印九九乘法表    

        for i in range(1,10):

                for j in range(1,i+1):

                    print('%s*%s=%s'%(j,i,j*i),end=' ')

                print()


猜你喜欢

转载自blog.csdn.net/zhou_le/article/details/80501213
今日推荐