python中的保留字介绍
python中的保留字介绍
在Python中,保留字(也称为关键字)是具有特殊含义的单词,不能用作标识符(如变量名、函数名等)。Python最新版本中有 35 个保留字
1. False:
if not True:
print(False)
2. None:
value = None
if value is None:
print("Value is None")
3. True:
if True:
print("This will always print")
4. and:
if True and False:
print("This won't print")
5. as:
import numpy as np
a = np.array([1, 2, 3])
6. assert:
assert 2 + 2 == 4, "Math is broken!"
7. async:
async def my_coroutine():
print("Coroutine is running")
8. await:
async def main():
await my_coroutine()
9. break:
for i in range(5):
if i == 3:
break
print(i)
10. class:
class MyClass:
def __init__(self):
self.value = 0
11. continue:
for i in range(5):
if i == 2:
continue
print(i)
12. def:
def my_function():
print("Hello, world!")
13. del:
my_list = [1, 2, 3]
del my_list[1]
print(my_list) # Output: [1, 3]
14. elif:
x = 10
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is between 10 and 20")
else:
print("x is 10 or less")
15. else:
x = 5
if x > 10:
print("x is greater than 10")
else:
print("x is 10 or less")
16. except:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
17. finally:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This will always execute")
18. for:
for i in range(5):
print(i)
19. from:
from math import sqrt
print(sqrt(16)) # Output: 4.0
20. global:
x = 0
def func():
global x
x = 1
func()
print(x) # Output: 1
21. if:
if x > 0:
print("x is positive")
22. import:
import math
print(math.pi)
23. in:
if 2 in [1, 2, 3]:
print("2 is in the list")
24. is:
a = [1, 2, 3]
b = a
print(a is b) # Output: True
25. lambda:
double = lambda x: x * 2
print(double(5)) # Output: 10
26. nonlocal:
def outer():
x = 1
def inner():
nonlocal x
x = 2
inner()
print(x) # Output: 2
outer()
27. not:
if not True:
print("This won't print")
28. or:
if True or False:
print("This will print")
29. pass:
def my_function():
pass # To be implemented later
30. raise:
raise ValueError("Invalid value")
31. return:
def add(a, b):
return a + b
print(add(1, 2)) # Output: 3
32. try:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
33. while:
i = 0
while i < 5:
print(i)
i += 1
34. with:
with open('file.txt', 'r') as f:
content = f.read()
35. yield:
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
for value in gen:
print(value)
作者:Colin♛