• 一步一步学Python(1) 基本逻辑控制举例和编码风格规范


    (1) 基本逻辑控制举例和编码风格规范

    1.while死循环

    2.for循环

    3.if,elif,else分支判断

    4.编码风格(官方建议)

    版本:Python3.4

    1.while死循环

    #function: endless loop
    import time
    i = 0
    while 1:
        i += 1
        print(i)
        time.sleep(3)

    执行效果: 

    >>> import time
    >>> i = 0
    >>> while 1:
    ...     i += 1
    ...     print(i)
    ...     time.sleep(3)
    ... 
    1
    2
    3
    ^CTraceback (most recent call last):
      File "<stdin>", line 4, in <module>
    KeyboardInterrupt
    >>> 

    2.for循环

    #function: usage "for"
    for i in range(3):
        print("old i = " + str(i))
        i += 1
        print("new i = " + str(i))

    执行效果: 

    >>> for i in range(3):
    ...     print("old i = " + str(i))
    ...     i += 1
    ...     print("new i = " + str(i))
    ... 
    old i = 0
    new i = 1
    old i = 1
    new i = 2
    old i = 2
    new i = 3
    >>> 

    3.if,elif,else分支判断

    #function: usage "if..elif..else.."
    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')

    执行效果:

    $ python3 if.py 
    Please enter an integer: -1
    Negative changed to zero
    $ python3 if.py 
    Please enter an integer: 0
    Zero
    $ python3 if.py 
    Please enter an integer: 1
    Single
    $ python3 if.py 
    Please enter an integer: 2
    More

    4.编码风格(官方建议)

    • 使用 4 空格缩进,而非 TAB。

      在小缩进(可以嵌套更深)和大缩进(更易读)之间,4空格是一个很好的折中。TAB 引发了一些混乱,最好弃用。

    • 折行以确保其不会超过 79 个字符。

      这有助于小显示器用户阅读,也可以让大显示器能并排显示几个代码文件。

    • 使用空行分隔函数和类,以及函数中的大块代码。

    • 可能的话,注释独占一行

    • 使用文档字符串

    • 把空格放到操作符两边,以及逗号后面,但是括号里侧不加空格: a = f(1, 2) + g(3, 4)

    • 统一函数和类命名。

      推荐类名用 驼峰命名, 函数和方法名用 小写_和_下划线。总是用 self 作为方法的第一个参数(关于类和方法的知识详见 初识类 )。

    • 不要使用花哨的编码,如果你的代码的目的是要在国际化环境。 Python 的默认情况下,UTF-8,甚至普通的 ASCII 总是工作的最好。

    • 同样,也不要使用非 ASCII 字符的标识符,除非是不同语种的会阅读或者维护代码。

  • 相关阅读:
    河北省科技创新年报统计系统分析
    《软件需求十步走》阅读笔记06
    《软件需求十步走》阅读笔记05
    《软件需求十步走》阅读笔记04
    河北科技创新平台年报统计
    《软件需求十步走》阅读笔记03
    《软件需求十步走》阅读笔记02
    《软件需求十步走》阅读笔记01
    案例分析
    2017秋季个人阅读计划
  • 原文地址:https://www.cnblogs.com/jyzhao/p/4055191.html
Copyright © 2020-2023  润新知