python初学者须知的一些编码建议

[原文链接] : http://www.techbeamers.com/top-10-python-coding-tips-for-beginners/

译者:本文内容非常基础,适合初期入门的读者。

Python编码建议:适用于初学者与老手

  1. 运行Python脚本

    对于大部分的UNIX系统,你可以按照下面的方式从命令行运行Python脚本。

    
    # run python script
    
    $ python MyFirstPythonScript.py
  2. 从Python解释器中运行Python程序

    Python的交互式解释器非常易于使用。在学习编程的初始阶段你可以尝试这种方式,并使用任何的Python命令。仅仅需要在Python控制台一条一条地敲入命令,答案将会立刻显示出来。

    Python控制台可以通过下面的命令开启:

    
    # start python console
    
    $ python
    >>> <type commands here>

    在本文中,所有>>>符号开头的代码都是指

  3. 使用enumerate()函数

    enumerate()函数给一个可迭代的对象增加一个计数器. 对象可迭代指该对象有一个 __iter__ 方法,该方法返回一个迭代器。它可以接受一个从零开始的一个顺序索引。当索引无效时会抛出一个IndexError

    enumerate()函数一个典型的例子是一个列表进行循环并保持其索引。为此,我们可以使用一个计数变量。不过对于这种情形,python给我们提供了一个更加漂亮的语法。

    
    # First prepare a list of strings
    
    subjects = ('Python', 'Coding', 'Tips')
    for i, subject in enumerate(subjects):
        print i, subject
    
    # Output:
    
    0 Python
    1 Coding
    2 Tips
  4. 集合(set)数据类型

    数据类型“set”是指一些对象的集合。从Python2.4开始就成为Python的一部分。一个集合(set)内所包含的对象都不相同且不可变。它是Python数据类型的一种,是对于数学世界中的实现。这也解释了为什么集合不像列表或元组那样允许多个相同的元素同时存在。

    如果你想创建一个集合,只需使用内置的set()函数即可,它可以接受一个序列或另外可迭代的对象。

    
    # *** Create a set with strings and perform search in set
    
    objects = {"python", "coding", "tips", "for", "beginners"}
    
    # Print set.
    
    print(objects)
    print(len(objects))
    
    # Use of "in" keyword.
    
    if "tips" in objects:
        print("These are the best Python coding tips.")
    
    # Use of "not in" keyword.
    
    if "Java tips" not in objects:
        print("These are the best Python coding tips not Java tips.")
    
    # ** Output
    
    {'python', 'coding', 'tips', 'for', 'beginners'}
    5
    These are the best Python coding tips.
    These are the best Python coding tips not Java tips.
    
    # *** Lets initialize an empty set
    
    items = set()
    
    # Add three strings.
    
    items.add("Python")
    items.add("coding")
    items.add("tips")
    print(items)
    
    # ** Output
    
    {'Python', 'coding', 'tips'}
  5. 动态类型

    在java, c++或一些其他的静态类型语言中,你必须指定函数返回值和每个函数参数的类型。相反,Python是是一个动态语言类型。在python中,你不需要显示地提供数据类型。基于我们所给的赋值,Python能够自动推断数据类型。对于动态类型的一个好的定义如下:

    “Names are bound to objects at run-time with the help of assignment statements. And it is possible to attach a name to the objects of different types during the execution of the program.”

    “命名在运行时通过赋值语句绑定到对象。在程序执行时可能将一个命名绑定到不同类型对象上。”

    下面的例子展示了一个函数如何检测它的参数,根据其数据类型的不同采取不同的操作。

    
    # Test for dynamic typing.
    
    from types import *
    def CheckIt (x):
    if type(x) == IntType:
    print "You have entered an integer."
    else:
    print "Unable to recognize the input data type."
    
    # Perform dynamic typing test
    
    CheckIt(999)
    
    # Output:
    
    
    # You have entered an integer.
    
    CheckIt("999")
    
    # Output:
    
    
    # Unable to recognize the input data type.
    
  6. == 与 = 操作符

    Python使用‘==’来比较,‘=’来赋值。Python不支持内联赋值,所以不会发生当你想进行比较操作时却意外发生赋值的情况。

  7. 条件表达式

    Python考虑了条件表达式。所以你不再需要在每个条件分支仅有一个赋值语句时写if ... else....

    试一下下面的例子:

    
    # make number always be odd
    
    number = count if count % 2 else count - 1
    
    # call a function if object is not None
    
    data = data.load() if data is not None else 'Dummy'
    print "Data collected is ", data
  8. 字符串连接

    你可以像下面这样使用‘+’进行字符串连接:

    
    # See how to use ‘+’ to concatenate strings.
    
    >>> print ‘Python’+’ Coding’+' Tips'
    
    # Output:
    
    Python Coding Tips
  9. __init__方法

    在一个类对象被实例化后, __init__方法会被立即调用。该方法对于执行预期的初始化操作非常有用。 __init__ 方法类似于c++, c#或java里面的构造函数。

    
    # Implementing a Python class as InitEmployee.py
    
    class Employee(object):
        def __init__(self, role, salary):
            self.role = role
            self.salary = salary
        def is_contract_emp(self):
            return self.salary <= 1250
        def is_regular_emp(self):
            return self.salary > 1250
    
    emp = Employee('Tester', 2000)
    if emp.is_contract_emp():
        print "I'm a contract employee."
    elif emp.is_regular_emp():
        print "I'm a regular employee."
    print "Happy reading Python coding tips!"

    上面代码的输出如下:

    [~/src/python $:] python InitEmployee.py
    I'm a regular employee.
    Happy reading Python coding tips!
  10. 模块

    为了使你的程序规模在不断增长时依旧能够可管理,你可能想要把他们分割成为几个小文件。Python允许你将多个函数定义放到一个文件并通过模块进行调用。你可以将模块导入其他脚本或程序。这些文件的扩展名必须为.py.

    
    # 1- Module definition => save file as my_function.py
    
    def minmax(a,b):
        if a <= b:
            min, max = a, b
        else:
            min, max = b, a
        return min, max
    
    # 2- Module Usage
    
    import my_function
    x,y = my_function.minmax(25, 6.3)
    print (x)
    print (y)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值