Python学习笔记1:基础

1.编码
默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。
你也可以为源文件指定不同的字符编码。在 #! 行(首行)后插入至少一行特殊的注释行来定义源文件的编码:

# -*- coding: utf-8 -*-
或
# -*- coding: cp-1252 -*-

2.标识符
第一个字符必须是字母表中字母或下划线 _ 。
标识符的其他的部分由字母、数字和下划线组成。
标识符对大小写敏感。

3.python保留字
保留字即关键字,我们不能把它们用作任何标识符名称。Python 的标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']
>>> 

4.注释
Python中单行注释以 # 开头,实例如下:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

# First comment
print("Hello world!")

Python中使用三个双引号或单引号来注释多行内容,实例如下:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

'''
First comment
Line 1
Line 2
'''

"""
Second comment
Line 1
Line 2
"""
print("Hello world!")

5.缩进
python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {} 。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:

if True:
    print("This is true")
else:
    print("This is false")

如果语句缩进数的空格数不一致,会导致运行错误:

if True:
    print("This is true")
else:
    print("This is false")
   print("This is error") # error

IndentationError: unindent does not match any outer indentation level

上一篇:第08组 Beta冲刺 (4/5)


下一篇:登陆!Let's Start Coding