Skip to content

Python 语句

Python语句是由Python解释器执行的代码指令。Python会按照代码中语句出现的顺序逐条执行它们。

Python语句示例

我们来看一些简单的语句示例。

python
count = 10  # statement 1
 
class Foo:  # statement 2
    pass    # statement 3

Python多行语句

Python 语句通常写在一行中。换行符标记语句的结束。如果语句很长,我们可以使用换行符(\)将其显式地分成多行。

让我们来看一些多行语句的例子。

python
message = "Hello There.\nYou have come to the right place to learn Python Programming.\n" \
          "Follow the tutorials to become expert in Python. " \
          "Don't forget to share it with your friends too."
 
math_result = 1 + 2 + 3 + 4 + \
              5 + 6 + 7 + 8 + \
              9 + 10
 
print(message)
print(math_result)

Python 语句

Python 支持在圆括号 ( )、方括号 [ ] 和花括号 { } 内进行多行续写。方括号用于列表对象,花括号用于字典对象。圆括号可用于表达式、元组和字符串。

python
message = ("Hello\n"
           "Hi\n"
           "Namaste")
 
math_result = (1 + 2 + 3 + 4 +
               5 + 6 + 7 + 8 +
               9 + 10)
 
prime_numbers_tuple = (2, 3, 5, 7,
                       11, 13, 17)
 
list_fruits = ["Apple", "Banana",
               "Orange", "Mango"]
 
dict_countries = {"USA": "United States of America", "IN": "India",
                  "UK": "United Kingdom", "FR": "France"}

一行可以包含多条语句吗?

我们可以使用分号(;)在一行中输入多个语句。

python
x = 1; y = 2; z = 3

Python 简单语句

Python 简单语句由一行代码组成。上面创建的多行语句也是简单语句,因为它们都可以写在一行里。接下来我们来看一些 Python 中重要的简单语句类型。

1. Python表达式语句

python
i = int("10")  # expression is evaluated and the result is assigned to the variable.
 
sum = 1 + 2 + 3  # statement contains an expression to be evaluated first.

2. Python赋值语句

python
count = 10  # value is assigned to the variable, no expression is evaluated
 
message = "Hi"

3. Python 断言语句

python
assert 5 < 10
assert (True or False)

4. Python pass 语句

python
def foo():
    pass  # pass statement

阅读更多关于Python 中 pass 语句的内容

5. Python del 语句

python
name = "Python"
del name  # del statement

6. Python 返回语句

python
def foo():
    return 10  # return statement

推荐阅读:Python 中的 return 语句

7. Python yield 语句

python
def yield_statement():
    yield 'Statement 1'  # yield statement

阅读更多关于Python 中 yield 的内容

8. Python raise 语句

python
def raise_example():
    raise TypeError('Exception Example')  # raise statement

阅读更多关于Python异常处理的内容

9. Python break 语句

python
numbers = [1, 2, 3]
for num in numbers:
    if num > 2:
        break  # break statement

阅读更多关于Python break 语句的内容

10. Python continue 语句

python
numbers = [1, 2, 3]
for num in numbers:
    if num > 2:
        continue  # continue statement
    print(num)

延伸阅读:Python continue 语句

11. Python 导入语句

python
import collections
import calendar as cal
from csv import DictReader

推荐阅读:Python 中的 import 语句

12. Python 全局语句

python
name = "Python"
 
def global_example():
    global name  # global statement
    name = "Flask"
 

print(name)  # prints Python
global_example()
print(name)  # prints Flask

13. Python 非局部变量语句

python
def outer_function():
    scope = "local"
 
    def inner_function():
        nonlocal scope  # nonlocal statement
        scope = "nonlocal"
        print(scope)
 
    inner_function()
    print(scope)
 
outer_function()

Python复合语句

Python复合语句包含一组其他语句,并会影响它们的执行。复合语句通常跨越多行。让我们简要了解几个复合语句。

1. Python if 语句

python
if 5 < 10:
    print("This will always print")
else:
    print("Unreachable Code")

推荐阅读:Python if-else语句

2. Python for 语句

python
for n in (1, 2, 3):
    print(n)

延伸阅读:Python for 循环

3. Python while 语句

python
count = 5
while count > 0:
    print(count)
    count -= 1

阅读更多关于Python while 循环的内容

4. Python try 语句

python
try:
    print("try")
except ValueError as ve:
    print(ve)

5. Python语句

python
with open('data.csv') as file:
    file.read()

6. Python 函数定义语句

Python函数定义是一个可执行语句。它的执行会将当前本地命名空间中的函数名绑定到一个函数对象。该函数只有在被调用时才会执行。

python
def useless():
    pass

7. Python 类定义语句

这是一个可执行语句。Python类定义定义了类对象。

python
class Data:
    id = 0

8. Python协程函数定义语句

python
import asyncio
 
async def ping(url):
    print(f'Ping Started for {url}')
    await asyncio.sleep(1)
    print(f'Ping Finished for {url}')

总结

Python 语句由 Python 解释器用于运行代码。了解 Python 中不同类型的语句很有帮助。

参考: