• 技术文章 >Python技术 >Python基础教程

    python控制语句的两大分类

    小妮浅浅小妮浅浅2021-08-20 17:40:14原创2578

    1、Python为迭代提供了标准的while语句和非常强大的for语句。当给定条件为真时,while语句将重复执行一段代码。

    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

    count=1

    while count<=5:

        print("河南加油!")

        count+=1

    #结果如下:

    河南加油!

    河南加油!

    河南加油!

    河南加油!

    河南加油!

      

    for item in '河南加油!':

        print(item)

    # 结果如下

      

    for i in range(5):

        print(i)

    # 结果如下

    0

    1

    2

    3

    4

      

    #通过for语句输出单个字符

    wordlist = ['cat','dog','rabbit']

    letterlist = []

    for aword in wordlist:

        for aletter in aword:

            letterlist.append(aletter)

             

    letterlist

    #结果如下:

    ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']

    2、分支语句允许程序员询问,然后根据结果采取不同的行动。

    大多数编程语言提供两种有用的分支结构:ifelse和if。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    import math

    n=float(input("请输入一个数"))

    if n < 0:

           print("Sorry,")

    else:

           print(math.sqrt(n))

    #结果:请输入一个数 3

    # 1.7320508075688772

      

    #多条件分支

    score=float(input("请输入一个数"))

    if score >= 90:

           print('A')

    elif score >= 80:

           print('B')

    elif score >= 70:

           print('C')

    elif score >= 60:

           print('D')

    else:

           print('F')

    # 请输入一个数 90 A

    以上就是python控制语句的两大分类,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python控制语句
    上一篇:python输入函数input的使用 下一篇:python编写程序的常见错误

    相关文章推荐

    • reload在python中的使用• python中socket如何建立服务器• python中socket建立客户连接• python中Roberts算子是什么• python中Prewitt算子如何理解• python中Sobel算子是什么• python中Sobel算子如何使用• python中Laplacian算子如何使用• python中Laplacian算子是什么• python输入函数input的使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网