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

快来打我* 2022-09-26 04:56 252阅读 0赞

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

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

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

  1. 运行Python脚本

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

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

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

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

    1. # start python console
    2. $ python
    3. >>> <type commands here>

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

  3. 使用enumerate()函数

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

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

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

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

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

    1. # *** 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.")
    2. # ** Output
    3. {
    4. 'python', 'coding', 'tips', 'for', 'beginners'}
    5. 5
    6. These are the best Python coding tips.
    7. These are the best Python coding tips not Java tips.
    8. # *** Lets initialize an empty set
    9. items = set()
    10. # Add three strings.
    11. items.add("Python")
    12. items.add("coding")
    13. items.add("tips")
    14. print(items)
    15. # ** Output
    16. {
    17. '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.”

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

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

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

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

  2. 条件表达式

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

    试一下下面的例子:

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

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

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

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

    1. # Implementing a Python class as InitEmployee.py
    2. class Employee(object):
    3. def __init__(self, role, salary):
    4. self.role = role
    5. self.salary = salary
    6. def is_contract_emp(self):
    7. return self.salary <= 1250
    8. def is_regular_emp(self):
    9. return self.salary > 1250
    10. emp = Employee('Tester', 2000)
    11. if emp.is_contract_emp():
    12. print "I'm a contract employee."
    13. elif emp.is_regular_emp():
    14. print "I'm a regular employee."
    15. print "Happy reading Python coding tips!"

    上面代码的输出如下:

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

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

    1. # 1- Module definition => save file as my_function.py
    2. def minmax(a,b):
    3. if a <= b:
    4. min, max = a, b
    5. else:
    6. min, max = b, a
    7. return min, max
    8. # 2- Module Usage
    9. import my_function
    10. x,y = my_function.minmax(25, 6.3)
    11. print (x)
    12. print (y)

发表评论

表情:
评论列表 (有 0 条评论,252人围观)

还没有评论,来说两句吧...

相关阅读

    相关 mysql优化一些建议

    1.为查询缓存优化查询 当很多相同的查询语句被执行了多次的时候,这些查询结果会被放到一个缓存中 2.善用EXPLAIN 3.若已确定只查询一条数据,加上LIMIT

    相关 编码一些建议

    1、尽量指定类、方法的final修饰符——虚拟机会想办法内联所有的final方法来减少方法执行时创建栈帧的数量,从而降低栈溢出的风险 2、尽量重用对象——重复new对象会增加