前言:
Python很方便,平时工作偶尔用来做一些小工具,需要参考的时候百度搜出来的东西实在不靠谱,遂决定根据官网的文档系统地学习一下,顺便给中文Python学习资料增加一点内容吧,适合对C++,java之类的面向对象语言熟悉,但是不了解Python的读者。
Python特性
环境配置就不多做赘述了,随便搜都有,编程基本知识也跳过,默认读者至少对函数、类、变量、字符等概念有一个了解,本人主打一个懒,能不写就不写,IDE这里推荐一下PyCharm跟VS Code,PyCharm集成度更高,内置的PEP8格式提醒很严格便于我们写出优雅的代码,VS Code需要自己折腾一下插件,支持各种语言和Markdown,用来写文档很舒服。
官网的特性介绍如下:
Some programming-language features of Python are:
- A variety of basic data types are available: numbers (floating point, complex, and unlimited-length long integers), strings (both ASCII and Unicode), lists, and dictionaries.
- Python supports object-oriented programming with classes and multiple inheritances.
- Code can be grouped into modules and packages.
- The language supports raising and catching exceptions, resulting in cleaner error handling.
- Data types are strongly and dynamically typed. Mixing incompatible types (e.g. attempting to add a string and a number) causes an exception to be raised, so errors are caught sooner.
- Python contains advanced programming features such as generators and list comprehensions.
- Python's automatic memory management frees you from having to manually allocate and free memory in your code.
大家都很熟了,总之就是面向对象、动态类型、自动内存管理啥的这年代很常见的高级语言的特性。
语法上一个很特别的地方在于Python的代码块不是用{}规定的,而是通过行首的空格或者tab,具体怎么用呢?优雅的代码离不开代码标准,Python官方给出了PEP8标准,根据PEP8的规定:
Use 4 spaces per indentation level.
行首应该使用4个空格键而非tab,同时tab跟空格也是不兼容的,tab空格混用将造成极其严重的后果(如果你像我刚开始一样用notepad++之类的IDE),但是按tab它舒服啊,所幸在PyCharm中可以通过ctrl+alt+L快速排版,解决了这个问题。
PEP8标准还规定了诸如函数命名、类命名、变量命名等规则,无非是驼峰命名法,PyCharm的自动提示会给出warning,照着修改就可以了,具体参考PEP8。
Hello world
OK,编程第一课,Hello world!我们的helloworld.py应该如下:
if __name__ == '__main__':
print('Hello world.')
使用python helloworld.py执行即可输出Hello world.
如前所述,if语句后面使用:
开始新的层级,并在新的层级开头添加4个空格。
和JS一样,python对字符跟字符串不做区分,所以可以用单引号定义字符串,当然双引号也是可以的,反正少按一个shift,用单引号比较方便,也不违反PEP8的规则,同时也有一些别的好处(如可以不用转义直接使用双引号)。
不同于C++和java,print
属于内建函数,无需引入任何包,__name__
则是helloworld这个module的内置属性,记录了module的名称:
__name__
The __name__ attribute must be set to the fully qualified name of the module. This name is used to uniquely identify the module in the import system.
在以下情况,__name__会被设置为__main__:
In Python, the special name __main__ is used for two important constructs:
- the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and
- the __main__.py file in Python packages.
那么什么是top-level environment of the program
呢?典型的就如上由python helloworld.py
命令指定helloworld这个module的__name__为__main__,另外一种方式是使用-m
参数指定一个module,python将会找到该module内部的__main__.py并执行它。
OK,至此,我们已经完成了一个Hello world程序,并对python的基本运行原理有了一个了解。