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

来源:互联网 发布:广告创意提案 知乎 编辑:程序博客网 时间:2024/05/19 22:56

[原文链接] : 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 stringssubjects = ('Python', 'Coding', 'Tips')for i, subject in enumerate(subjects):    print i, subject
    # Output:0 Python1 Coding2 Tips
  4. 集合(set)数据类型

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

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

    # *** Create a set with strings and perform search in setobjects = {"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'}5These are the best Python coding tips.These are the best Python coding tips not Java tips.
    # *** Lets initialize an empty setitems = 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 testCheckIt(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 oddnumber = count if count % 2 else count - 1# call a function if object is not Nonedata = 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.pyclass 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 > 1250emp = 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.pyI'm a regular employee.Happy reading Python coding tips!
  10. 模块

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

    # 1- Module definition => save file as my_function.pydef minmax(a,b):    if a <= b:        min, max = a, b    else:        min, max = b, a    return min, max
    # 2- Module Usageimport my_functionx,y = my_function.minmax(25, 6.3)print (x)print (y)
0 0