Python 语法
Python 语法和其他主流语言有所区别:采用缩进表示代码段,采用换行表示语句结束,
不同于其他语言,Python 采用缩进表示代码块。
缩进是代码行开头的空格,很多其他语言中,代码的缩进只是为了可读性。而 Python 则不同,Python 的缩进代表了代码块。
如下面的 if 条件语句中的代码块必须有缩进:
if 5 > 2:
print("Five is greater than two!")
如果你没有缩进,Python 会给你一个错误:
if 5 > 2:
print("Five is greater than two!")
Python 命令行中返回如下错误:
>>> if 5 > 2:
... print("Five is greater than two!")
File "<stdin>", line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block
缩进的空格数没有限制,但必须至少为一个。
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
同一个代码块中使用相同数量的空格,否则 Python 会给你一个错误:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python 命令行中返回如下错误:
>>> if 5 > 2:
... print("Five is greater than two!")
... print("Five is greater than two!")
File "<stdin>", line 3
print("Five is greater than two!")
^
IndentationError: unexpected indent
Python 变量
在 Python 中,没有声明变量的关键字,直接声明并赋值变量即可。
Python 中的变量:
x = "Hello, World!"
Python 函数
在 Python 中,使用 def
关键字定义函数。
一个简单的函数:
def log(message):
print(message)
log('Hello World')
Python 语句
Python 使用换行作为语句结束的标记。也就是说一个 Python 语句通常占用一样。
如下的两个变量初始化语句:
x = "Hello, World!"
如果语句需要跨行,可以使用反斜杠 \
。
a = 1
b = 2
c = a +\
b
print(c)
或者使用小括号实现语句跨行:
a = 1
b = 2
c1 = (a +
b)
print(c1)
如果多个语句位于同一行中,可以使用分号 ;
结束语句:
a = 1;b = 2
c1 = (a +
b)
print(c1)
Python 注释
Python 代码注释以 #
开头, 当前行 #
之后的文本都是注释。
Python 中的注释:
#This is a comment.
print("Hello, World!")
Python 关键字
关键字 | 描述 |
---|---|
and |
逻辑运算符。 |
as |
创建别名。 |
assert |
用于调试。 |
break |
跳出循环。 |
class |
定义类。 |
continue |
继续循环的下一个迭代。 |
def |
定义函数。 |
del |
删除对象。 |
elif |
在条件语句中使用,等同于 else if。 |
else |
用于条件语句。 |
except |
处理异常,发生异常时如何执行。 |
False |
布尔值,比较运算的结果。 |
finally |
处理异常,无论是否存在异常,都将执行一段代码。 |
for |
创建 for 循环。 |
from |
导入模块的特定部分。 |
global |
声明全局变量。 |
if |
写一个条件语句。 |
import |
导入模块。 |
in |
检查列表、元组等集合中是否存在某个值。 |
is |
测试两个变量是否相等。 |
lambda |
创建匿名函数。 |
None |
表示 null 值。 |
nonlocal |
声明非局部变量。 |
not |
逻辑运算符。 |
or |
逻辑运算符。 |
pass |
null 语句,一条什么都不做的语句。 |
raise |
产生异常。 |
return |
退出函数并返回值。 |
True |
布尔值,比较运算的结果。 |
try |
编写 try…except 语句。 |
while |
创建 while 循环。 |
with |
用于简化异常处理。 |
yield |
结束函数,返回生成器。 |
执行 Python 语句
正如我们在上一章中学到的,可以直接在命令行中编写并执行 Python 语句:
>>> print("Hello, World!")
Hello, World!
或者将代码写在一个 python 文件(.py
扩展名),并在命令行中运行:
python myfile.py