查看Python3的全部关键字方法
import keyword
print(keyword.kwlist)
print(len(keyword.kwlist))
我们可以看到Python3有33个关键字
break | False | None | True | and | as | assert |
class | continue | def | del | elif | else | except |
finally | for | from | global | if | import | in |
is | lambda | nonlocal | not | or | with | yield |
pass | raise | return | try | while |
针对每一个关键字我们做出简单的介绍
class MyException(Exception):pass
try:
#some code here
raise MyException
except MyException:
print "MyException encoutered"
finally:
print "Arrive finally"
for letter in 'Python': # 字符串
print '当前字母 :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 数组
print '当前水果 :', fruit
print "Good bye!"
func = lambda x:x+1
>>> func(1)
>>>2
>>>func(2)
>>>3
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
>>> print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>> print reduce(lambda x, y: x + y, foo)
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
def make_counter_test():
mc = make_counter()
print(mc())
print(mc())
print(mc())
a = [-1,3,'aa',85] # 定义一个list
del a[0] # 删除第0个元素
del a[2:4] # 删除从第2个到第3个元素。
class controlled_execution:
def _enter_(self):
set things up
return thing
def _exit_(self,type,value,traceback):
tear thing down
with controlled_execution() as thing:
some code
assert len(mylist) >= 1
def f(arg):
pass # a function that does nothing (yet)
class Myclass:
pass # a class with no methods(yet)
class MyException(Exception):pass
try:
raise MyException
except MyException:
print('MyException encoutered')
finally:
print('Arrive finally')
(adsbygoogle = window.adsbygoogle || []).push({});