Python 基础教程

Python 是一门编程语言,就像 C\C++、Fortran、Matlab、BASIC、PHP 等语言,但它有如 下的特点:

  • 是一门解释性的语言(与编译的语言相对),并且可以交互式使用。有很多 Python 的解 释器可以用来执行命令和脚本。
  • 开源协议下的自由软件,可以个人和开发商业软件都可以免费使用。
  • 跨平台。
  • 语法简洁明了,代码可读性强。
  • 从网站架构到科学计算,对于不同的应用,Python 都有大量高质量的软件包可以使用。
  • 非常容易和其它语言对接,特别是 C 和 C++ 语言。
  • 是面向对象和动态类型的语言。
    • 这个世界是面向对象的。
    • 在一个程序当中, 同一个变量可以包含不同类型的对象。

Python 的设计原则

why@why-XPS-15-9530:~$ ipython3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
Type "copyright", "credits" or "license" for more information.

IPython 5.5.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

下面是中文翻译,来自这里

Python之禅 by Tim Peters

优美胜于丑陋(Python 以编写优美的代码为目标)

明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)

简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)

复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁)

扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)

间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)

可读性很重要(优美的代码是可读的)

即便假借特例的实用性之名,也不可违背这些规则(这些规则至高无上)

不要包容所有错误,除非你确定需要这样做(精准地捕获异常,不写 except:pass 风格的代码)

当存在多种可能,不要尝试去猜测

而是尽量找一种,最好是唯一一种明显的解决方案(如果不确定,就用穷举法)

虽然这并不容易,因为你不是 Python 之父(这里的 Dutch 是指 Guido )

做也许好过不做,但不假思索就动手还不如不做(动手之前要细思量)

如果你无法向人描述你的方案,那肯定不是一个好方案;反之亦然(方案测评标准)

命名空间是一种绝妙的理念,我们应当多加利用(倡导与号召)

注: 上面的原则有一定的普适性,如

  1. 数学
  2. 写作

Python 交互环境 IPython 终端

利用 Python 交互环境,是利用 Python 语言解决问题的最便捷方式,逐步地执行代码可以 帮助我们更好地测试和理解算法。

下面演示 IPython 的交互用法, 在命令行终端输入 ipython3

why@why-XPS-15-9530:~$ ipython3 
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
Type "copyright", "credits" or "license" for more information.

IPython 5.5.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]:
In [1]: print("Hello World") # 回车执行命令
Hello World

In [2]:

In [2]: print?
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type:      builtin_function_or_method

也可以把命令代码放到文本文件中,包含可执行代码命令的文本文件称为脚本。如把下 面的内容

s = 'Hello world'
print(s)

放入脚本文件 my_file.py, 然后在 IPython

In [3]: run my_file.py
Hello world!
In [4]: s
Out[4]: 'Hello world!'

In [5]: whos
Variable   Type    Data/Info
----------------------------
s          str     Hello world!

注: 脚本(script)是命令的集合,用起来很方便,但最大缺点是无法重用

IPython 操作技巧

历史命令

利用 <UP><DOWN> 键遍历已经输入过的命令。

Tab 键补全

In [6]: x = 10

In [7]: x.<TAB>
           x.bit_length  x.from_bytes  x.real
           x.conjugate   x.imag        x.to_bytes
           x.denominator x.numerator

魔法函数 (magic functions)

魔法函数 (magic functions) 是 IPython 中以 %%% 开头的命令,它们后面的 参数不需要放到括号里。这些函数可以极大的方便用户与 IPython 的交互, 提高交互效 率。

粘贴代码

>>> for i in range(3):
        print(i)
In [8]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:>>> for i in range(3):
        print(i)
::<EOF>
0
1
2

计时

In [7]: %timeit x=10
100000000 loops, best of 3: 10.3 ns per loop

调试

In [12]: x === 10
  File "<ipython-input-12-8e8bc565444b>", line 1
    x === 10
        ^
SyntaxError: invalid syntax


In [13]: debug
> /usr/lib/python3/dist-packages/IPython/utils/py3compat.py(152)input()
    150     # to forward requests to a frontend.
    151     def input(prompt=''):
--> 152         return builtin_mod.input(prompt)
    153
    154     builtin_mod_name = "builtins"

ipdb> locals()
{'prompt': ':'}
ipdb>

魔法函数索引命令

In [14]: %quickref

Python 语言基础

第一步

Hello World!

In [1]: print("Hello, world!")
Hello, world!

变量

In [2]: a = 3

In [3]: b = 2*a

In [4]: type(b)
Out[4]: int

In [5]: print(b)
6

In [6]: a*b
Out[6]: 18

In [7]: b = 'hello'

In [8]: type(b)
Out[8]: str

In [9]: b + b
Out[9]: 'hellohello'

In [10]: 2*b
Out[10]: 'hellohello'

Tips:

  1. 定义了两个变量
  2. 代码中没有声明变量的类型
  3. 在 C 中, int a = 3;
  4. 变量的类型可以改变

基本类型

数值类型

  • Python 支持如下标题数值类型:
    1. Integer
    2. Floats
    3. Complex
    4. Booleans
  • Python 可以当做一个计算器
    1. +
    2. -
    3. *
    4. /
    5. //
    6. %
    7. **

容器

  • 列表(Lists)

    1. 定义 (Define) colors = ['red', 'blue', 'green', 'black', 'white']
    2. 索引(Indexing)
    3. 切片(Slicing)[start:stop:stride]
      • 上面的三个参数都是可选的
    4. list 是一个 mutable 对象, 可以被修改。
    5. list 可以包含不同的类型对象。
    6. 添加和移除 list 中的对象
    7. 顺序取反(in-place or out-place)
    8. 拼接和重复操作 +*
    9. 排序 (in-place or out-place)
    10. list 中的方法成员与数据成员(解释面向对象)
    11. 键来发现新的方法
  • 字符串 (Strings)

    1. 不同字符串定义的语法(四种), 展示错误的定义方式。
    2. 索引
    3. 切片
    4. 不可变对象 (immutable object),但可以基于原来的字符串创建新的字符串。
    5. 字符串有很多有用的方法, 用 <TAB>help(str) 发现更多新方法。
    6. 字符串格式化。
  • 字典 (Dictionaries)
    1. 定义
    2. 索引
    3. 添加
    4. 键值对 (maps keys to values)
    5. 无序容器
  • 元组 (Tuples)
    1. 定义
    2. 索引
    3. 切片
    4. 不可变的列表
  • 集合 (Sets)
    1. 定义,包括无序且唯一的元素

赋值操作

  • 给一个绑定重新绑定一个名字。
  • 等号右边的表达式计算后,创建或获得一个新对象。
  • 等号左边的名字被分配或者说绑定到右边的新对象上。
  • 一个对象绑定多个名字。
  • 要改变一个对象的数据(in place),要用索引或者切片。
  • 可变 (mutable) 和不可变 (immutable) 的区别。
    • 可变对象的内部可以修改。
    • 不可变对象一旦创建就不可以修改。

控制流 (Control Flow)

  • if/elif/else
    In [11]: if 2**2 == 4:
      ...:     print('Obvious!')
      ...:
    Obvious!
    
  • 代码块是通过缩进(Indentation)来标示的,请注意在 Python 交互终端或脚本文件 中都要严格遵守缩进深度,不同缩进深度表示不同的代码块。 深度!
  • for/range
    • 索引迭代
    • 值迭代,更可读
  • while/break/continue
    • z = 1 + 1j, z = z**2 + 1 例子
    • break
    • continue
  • 条件表达式
    • ==
    • is
    • in
    • not
  • 容器的迭代
    • 找出单词中的元音
    • 把一句英文中单词逐个打印出来
  • 同时获取容器的值和索引的两种方法
    • 索引迭代
    • enumerate
  • 字典的迭代
  • 列表内涵表达式 (List Comprehensions)
    • [i**2 for i in range(4)]
    • for 循环的时间比较
    • 计算 的值

定义函数

results matching ""

    No results matching ""