Python学习笔记(1)——基础语法笔记

Python常用IDE

原始的Python自带的解释器是IDLE,常用的PythonIDE有Anaconda带的Jupyter Notebook,使用这种IDE的时候,安装后只需要在cmd中输入jupyter notebook即可。还有一种比较常用的Python IDE是Pycharm。

python退出

在windows的命令行,或ubuntu中,退出Python,使用exit()即可。

Python基础语法

(1)注释#,扩展名.py

先看一段代码,如下所示:

1
2
3
4
5
6
7
8
9
biotest@biotest-VirtualBox:~/python3/01basic$ cat hello.py
#!/usr/bin/python3
# This is a comment
print("Hello, python3!")
# This is another comment
biotest@biotest-VirtualBox:~/python3/01basic$ python3 hello.py
Hello, python3!

从上面的这段代码可以知道这些信息:

  1. 在Python中,注释是以#进行标识的;
  2. Python程序文件以.py为后缀。
  3. 开头的代码指明了Python3解释的位置,即#!/usr/bin/pyhton3(其实我发现,不加这一行也能运行)。

除了#可以作为注释外,还可以使用多个#'''"""作为注释,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/python3
# 第一个注释
# 第二个注释
'''
第三注释
第四注释
'''
"""
第五注释
第六注释
"""
print ("Hello, Python!")

(2)行与缩进

Python语法的一大特点应时使用缩进来表示代码块,不需要使用大括号,在下面的例子中,第二行与第四行,必须要缩进4个字符,才能正常运行,否则就会出错,如下所示:

1
2
3
4
if True:
print ("True")
else:
print ("False")

(3)多行语句与引号

如果语句比较长,可以使用反斜杠(\)来实现多行语句,格式如下所示:

1
2
3
total = item_one + \
item_two + \
item_three

但是在[]{}()中,不需要使用反斜杠,如下所示:

1
2
total = ['item_one', 'item_two','item_three',
'item_four','item_five']

使用3个双引号,可以直接换行,如下所示:

1
2
3
4
5
6
7
>>> s3 = """hello,
... world,
... this is a multiline statements"""
>>> print(s3)
hello,
world,
this is a multiline statements

其实这段代码就相当下面的代码:

1
2
3
4
5
>>> s3 = "hello,\nworld,\nthis is a multiline statements."
>>> print(s3)
hello,
world,
this is a multiline statements

三引号,双引号和单引号的区别

看下面的案例就明白了:

1
2
3
4
5
6
>>> s4 = 'Let\'s go'
>>> print(s4)
Let's go
>>> s5 = "Let's go"
>>> print(s5)
Let's go

只使用单引号的话,如果字符串里还有单引号,那么需要进行转义,或者说是如果双引号里面还有双引号,也需要转义。

(4)转义字符

先看一个案例,如下所示:

1
2
3
4
5
6
>>> print(str1)
C:
ow
>>> str2 = 'c:\\now'
>>> print(str2)
c:\now

从这个案例中可以知道,在用Python处理目录时,需要对斜杠进行转义,如果目录的字符串比较长,例如C:\Program Files\Intel\WiFi\Help,那就可以在这个字符串前面加上一个r,如果最后要以斜杠结尾,那么只需要在最后使用转义符号即可,如下所示:

1
2
3
4
5
6
>>> str3 =r'C:\Program Files\Intel\WiFi\Help'
>>> print(str3)
C:\Program Files\Intel\WiFi\Help
>>> str4 =r'C:\Program Files\Intel\WiFi\Help''\\'
>>> print(str4)
C:\Program Files\Intel\WiFi\Help\

关键字keyword

Python的关键字指的Python编译器自己使用的,用户不可以使用,也就是说用户在定义函数,变量的时候不能使用Python自己的关键字,Python的关键字可以通过导入keyword包来查看,如下所示:

1
2
3
4
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>>

Python帮助文档查阅

(1)help函数

使用help函数可以查看某个函数的帮助,也可以查看所用模块的名称,如下所示:

查看print这个函数的帮助:

1
2
3
4
5
6
7
8
9
10
11
12
>>> help(print)
Help on built-in function print in module builtins:
print(...)
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.

查看math这个包以及这个包中ssqrt这个函数的帮助,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> import math
>>> help(math)
Help on built-in module math:
NAME
math
DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(...)
acos(x)
Return the arc cosine (measured in radians) of x.
-- More --
>>> help(math.sqrt)
Help on built-in function sqrt in module math:
sqrt(...)
sqrt(x)
Return the square root of x.

模块导入

使用import可以加载某个模块,例如import math就加载了math这个模块,使用dir()这个函数可以查看这个模块的成员,如下所示:

1
2
3
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

在Python中,模块的导入有两种形式,如下所示:

形式1:import module-name,import后面跟空格,然后是模块名称,例如import os

形式2:from module1 import module11,其中module1是一个大模块,里面还有子模块(通常是某个函数)modeule11,我们只想用module11,就可以这么写。

(1)内置函数与模块

内置函数

内置函数不需要导入任何模块即可直接使用,执行下面的命令可以列出所有内置函数和内置对象,如下所示:

1
2
3
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
... ...

内置模块

内置模块的查看方法如下所示:

1
2
3
4
>>> import sys
>>> print(sys.builtin_module_names)
('_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_csv', '_datetime', '_findvs', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_sre', '_stat', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')
>>>

对象

在python中,一切都是对象,每个对象在内存都中有自己的一个地址,这就是它的身份,可以通过id()函数来查看它们,如下所示:

1
2
3
4
5
6
7
>>> id(1)
10943008
>>> id(print())
10353568
>>> id("c")
139838545314064

参考资料

1. Python3教程|菜鸟教程