Python所有 关键字的解释

203 阅读7分钟

所有Python 关键字的解释

def

def 关键字允许我们编写自己的函数--函数是小代码块,可以随意重复使用。

# defining a function hello
def hello():
  print('hello')

# calling (using) the function hello
hello()

return

return 关键字表示函数的输出。

def add10(n):
  return n + 10

x = add10(4)
print(x)

# 14

^ 在这里,n + 10 位于 return 关键字的右侧,因此 n+10 是函数的输出。

注意--函数中的返回语句运行后不会再运行任何内容。

yield

yield 关键字也表示函数的输出。但与 return 语句不同的是,在 yield 运行后,stuff 仍然可以运行,这也意味着我们的函数可以有多个输出结果

def test():
  yield 1
  yield 2
  yield 3
  yield 4

for n in test():
  print(n)

# 1
# 2
# 3
# 4

^ 在函数中使用 yield 使其成为生成器函数,这意味着它有多个输出,我们需要使用 for 循环来调用它。

lambda

lambda 关键字允许我们编写小型匿名函数。

def add100(n):
  return n + 100

下面是一个使用 def 定义的普通函数

# lambda function_inputs: function_output

add100 = lambda n: n+100

下面是使用 lambda 定义的完全相同的函数

lambda n: n+100

^ lambda 函数是匿名的,因为给它取名是可选的。在这里,我们去掉了它的名字,它就变成了匿名函数。

None

None 关键字表示 None 类型,它什么也不表示。

def hello():
  print('hello')

x = hello()  # hello

print(x)     # None

^ 如果我们在函数中不返回任何内容,它默认返回 None。

with

with 关键字允许我们使用上下文管理器。

with open('a.txt') as f:
  # do stuff with f

^ 在这里,open('a.txt') 就是相关的上下文管理器。它包含两个特殊方法 __enter__ 和 __exit__,分别在 with 代码块的开始和结束时运行。

在这种情况下,当 with 代码块结束后,__exit__ 将运行以正确关闭文件 a.txt,从而防止内存泄漏和其他不好的事情发生。

as

as 关键字允许我们使用别名。

with open('a.txt') as f:
  # do stuff

^ 在这里,open('a.txt')返回的对象被赋予了别名 f,这样我们就可以方便地引用它。

import numpy as np

^ 在这里,我们导入了 numpy,但给它起了一个别名 np--这意味着从现在起,当我们要引用 numpy 时,只需使用 np 即可。

import 舶来品

import 关键字允许我们在代码中导入其他 Python 库和模块。

import numpy as np
import pandas as pd
import requests

^ 这非常有用,因为有很多 Python 库能让我们做很多很酷的事情。

from

使用 from 关键字,我们可以导入模块的特定部分,而不是整个模块。

from numpy import array

^ 在这里,我们不导入整个 numpy,而只导入数组

from requests import get, post

^ 在这里,我们只从请求中导入获取和发布功能

del

del 关键字允许我们删除代码中的内容。

a = 4
b = 5

del b

print(a)  # 4
print(b)  # ERROR

^ 在这里,我们删除了 b,因此当我们尝试打印 b 时会出现错误

d = {'apple':4, 'orange':5, 'pear':6}
del d['apple']

print(d)

# {'orange':5, 'pear':6}

^ 在这里,我们删除了 d['apple'],因此'apple':4 键值对被删除。

True & False

True 和 False 是布尔类型中仅有的两个值,我们在条件语句中使用它们。

if True:
  print('this will run')

if False:
  print('this will never run')

and, or & not

and or 和 not 是逻辑运算符,可用于包含多个条件的条件语句中。

x = 5
if x > 3 and x < 7:
  print('x is more than 3 and less than 7')

^ 并使整个表达式的两个条件都必须为 True

x = 5
if x > 3 or x < 7:
  print('either one condition needs to be True for this to print')

^ 或使表达式至少有一个条件为真,整个表达式才为真

print(not True)    # False
print(not False)   # True

^ 不是简单地切换 True 和 False

if, elif & else if, elif & else

if elif 和 else 用于编写条件语句。

score = 57

if score >= 90:
  print('grade A')

elif score >= 80:
  print('grade B')

elif score >= 70:
  print('grade C')

else:
  print('fail')
  • 如果是强制性的,则只能有 1 个 "如果 "区块。
  • elif 是可选项,可以有任意多个 elif 块
  • else 是可选项,并且只能有 1 个 else 块

type

通过 type 关键字,我们可以获取变量的数据类型

a = 1
print(type(a))   # <class 'int'>

b = 'apple'
print(type(b))   # <class 'str'>

class

类关键字用于创建类,然后对类进行初始化以创建对象。

class Dog:
  pass

dog = Dog()

^ 在这里,Dog 是一个类,而 dog 是一个对象

for

for 关键字用于编写 for 循环,该循环用于重复有限次数的操作。

for i in range(5):
  print('hello')

^ 在这里,我们使用 for 循环重复 print('hello') 5 次

while

while 关键字用于编写 while 循环,该循环用于无限重复操作,直到满足特定条件。

n = 1

while n < 3:
  print(n)
  n += 1

# 1
# 2
# 3

pass

pass 关键字什么也不做。我们通常将其用作尚未决定如何编写的代码的占位符。

def hello():
  pass

break

在 for 循环或 while 循环中使用 break 关键字时,会立即停止循环。

for i in range(1, 11):
  print(i)

  if i == 3:
    break

# 1
# 2
# 3

^ 在这里,我们在 i == 3 时中断,这就是为什么我们的整个 for 循环会在此时停止,之后不会再发生任何事情。

continue

在 for 循环或 while 循环中使用 continue 关键字时,会立即停止当前迭代,并跳转到下一次迭代。这并不会停止整个循环

for i in range(1, 6):
  if i == 3:
    continue

  print(i)

# 1
# 2
# 4
# 5

^ 在这里,当 i == 3 时,我们继续并直接跳到下一次迭代,但不会像 break 那样停止整个循环。

try & except

try 关键字用于尝试可能导致错误的代码,而 except 关键字用于定义如何处理 try 代码块产生的任何错误。

try:
  x = 1 + 'apple'
except:
  print('error!!')

# error!!

^ 在这里,我们试图将一个整数与一个字符串相加,这会导致错误,从而运行 except 代码块。

finally

finally 代码块用于 try 和 except 之后,无论 try 代码块中是否发生错误,finally 代码块中的内容都将始终运行。

try:
  x = 1 + 'apple'
except:
  print('error!!')
finally:
  print('this will always run')

# error!!
# this will always run

我们通常使用 finally 来运行必须运行的清理代码,例如关闭文件

assert

我们使用断言作为正确性检查。如果我们断言条件,而条件评估为 True,则不会发生任何事情。但如果条件评估为 "假",我们就会得到一个 AssertionError。

x = 1
assert type(x) == int

# nothing happens
x = 'apple'
assert type(x) == int

# AssertionError

raise

我们使用 raise 来强制导致异常或错误发生。

x = 1

if type(x) != int:
  raise Exception('x must be an integer!!')

# nothing happens
x = 1

if type(x) != int:
  raise Exception('x must be an integer!!')

# Exception:  x must be an integer!!

match & case

match 和 case 可用作 if-else 块的替代。

fruit = 'appple'

match fruit:
  case 'apple':
    print('apple juice')
  case 'orange':
    print('orange pie')
  case 'pear':
    print('pear cake')

# apple juice

^ 在这里,由于 fruit == 'apple','apple'情况发生,我们打印苹果汁

in

in 关键字用于检查某物是否在其他事物的内部。

fruits = ['apple', 'orange', 'pear']

print('apple' in fruits)      # True
print('pineapple' in fruits)  # False

is

is 关键字用于检查两个变量是否指向同一对象

a = ['apple', 'orange']
b = a

print(a is b)    # True

a = ['apple', 'orange']
b = ['apple', 'orange']

print(a is b)    # False

async await

async 和 await 关键字用于编写异步 Python 函数,我们可以并发运行而不是按顺序运行。

async def my_coroutine():
    print('coroutine started')
    await asyncio.sleep(1)
    print("coroutine ended")

global

global 关键字用于定义变量应引用全局变量。

x = 5

def test():
  x = 100

test()
print(x)    # 5

^ 在这里,test() 运行,x = 100 运行,但在测试函数中,x 位于本地作用域,因此不会覆盖全局 x

x = 5

def test():
  global x
  x = 100

test()
print(x)    # 100

^ 在这里,全局 x 使 x 指向全局 x,这就是为什么设置 x = 100 也会影响全局 x 的原因。

nonlocal

非本地关键字的行为与全局关键字类似,但它适用于嵌套函数内部的变量。

def test():
  x = 5
  
  def test2():
    nonlocal x
    x = 100

  test2()
  print(x)

test()

# 100