1Python基本元素
1.1Python变量、名字和对象
Python中所有数据以对象形式存在。Python是强类型,不能更改已经定义的对象类型,只能更新该对象的值。
赋值语句,使用“=”号赋值。
变量名组成:不能以数字开头,不能是关键字。
- 字母(a-Z)
- 数字(0-9)
- 下划线(_)
数字:Python支持整数浮点数计算。
运算符:
1.+加法
2.-减法
3.*乘法
4./浮点数除法
5.//整除
6.%取模(求余)
7.**幂运算
示例1:
#注释
#1.Python变量
#创建了a名字的对象,并将值赋给a
a = 1
print(a)
b = a
print(b)
#获取类型
#int
print(type(a))
#int
print(type(b))
#str
print(type('abc'))
#float
print(type(33.2))
#2Python数字
#整数
a = 5
#0不能作为前缀数字
#a = 05
a = +5
a = -5
#运算符+ ,-,*,/,//,%,**
a = a + 1
a = a - 1
a = a * 1
a = a / 1
a = a // 1
a = a % 1
#简化写法
a += 1
a -= 1
a *= 1
a /= 1
a //= 1
a **= 1
a %= 1
#得到余数和商
print(divmod(9,5))
#相当于
9 // 5
9 % 5
1.2运算符优先级
一般我们为了保证程式可阅读性,复杂计算通过添加括号来表明优先级。
1.[v1,v2],{v1,v2},{k1:v1,},()列表集合字典的创建和推导,括号;
2.seq[n],seq[n:m],func(),obj.attr,索引,切片,函数调用,属性引用;
3.**幂运算;
4.正号,负号,~x((位求反);
5.*,/,//,%;
6.+,-;
7.<<,>>位左移右移;
8.&;
9.|;
10.关系运算,比较运算==,<>,in,not in等等;
11.not x,布尔取非;
12.and 布尔;
13.or 布尔;
14.if else;
15.lambad表达式;
1.3进制基数
Python进制表示
示例1:
#进制
#二进制0b开头
#八进制0o开头
#十六进制0x开头
#十六进制0-9,A-F
print(0b110)
#8^2+8^1 = 72
print(0o110)
#16^2 *1+ 16^1*1+16^0*0 = 272
print(0x110)
1.4数据类型
int数据类型转换
示例1:
#类型转换
#布尔值:True,False
print(int(True))
print(int(False))
#浮点数转换
print(int(11.2))
#科学技术法
print(int(1.2e4))
#字符串
print(int('-22'))
#无法转换小数点字符串,科学计数法字符串
#print(int('23.3'))
整数类型大小
示例1:
#数据类型
#int类型大小
#python2,int类型为32位整数,long为64位整数
#python3,int类型可以存储任意长度大小整数
浮点数转换
示例1:
#浮点数转换
print(float(True))
print(float(False))
print(float('22.3'))
print(float('1.3e23'))
字符串,可以使用单引号,双引号创建字符串类型,也可以使用双引号包裹单引号,或使用单引号包裹双引号,或者使用三个单引号,或者使用三个双引号。
示例1:
#字符串
#单引号,双引号,三单引号,三双引号创建字符串
print('hello')
print("hello1")
print("hello 'tom'")
print('hello "tom"')
print('''hello''')
print("""hello""")
#创建空字符串
a = ''
#str()类型转换
str(22.2)
str(1.0e3)
str(True)
#转义\使用
#\n换行
print('a;\nb;\nc;\n')
#\b制表符
print('a;\bb;\bc;\b')
#转义单引号双引号
print('a\"hello\";\'hello\'')
#字符串拼接
print('hello' + 'world')
#字符串复制
print('hello\n'*4 + 'world')
#字符串提取[偏移量]
str1 = 'hello world'
#偏移量0-lenth(str)-1
print(str1[0])
#从右到左,-1开始
print(str1[-2])
#分片操作
#[start:end:step]
#从头到尾复制
str2 = str1[:]
#从start位置开始
str2 = str1[6:]
#从开始到end-1位置
str2 = str1[:5]
#从start到end-1
print(str1[1:2])
#负数操作
print(str1[-2:])
print(str1[:-4])
#步长操作
#每隔step取1字符
print(str1[::2])
#从右至左,取字符
print(str1[::-2])
#获取字符串长度
print(len(str1))
#字符串类型方法
#默认使用空格,换行符,制表符,分割
#可以传入参数指定分割符号
print(str1.split())
#字符串合并
#将字符串类型列表合并字符串
print(','.join(['hello','world']))
#开头,结尾判断
print(str1.startswith('hel'))
print(str1.endswith('world'))
#查找字符串
print(str1.find('w'))
#最后一次出现偏移
print(str1.rfind('l'))
#字符串计数
print(str1.count('l'))
#判断是否是字符串只包含数字,字母
print(str1.isalnum())
#大小写转换
str1 = 'hello world,hello Bei,'
#删除结尾相同字符
print(str1.strip(','))
#首字母大写,其余单词字母小写
print(str1.capitalize())
#所有单词首字母大写
print(str1.title())
#所有字母大写
print(str1.upper())
#所有字母小写
print(str1.lower())
#所有字母大小写互转
print(str1.swapcase())
#字符串排版
#居中
print(str1.center(50))
#靠左
print(str1.ljust(50))
#靠右
print(str1.rjust(50))
2Python容器
Python容器:列表,元组tuple,字典,集合,这些数据类型可以包括各种数据类型对象的序列。
2.1列表
字符串是不可变的,而列表是可变的序列,可以添加,修改,删除其中元素,而字符串的各个字符不能修改。
示例1:
#python列表
#使用[],list()创建列表
list1 = []
list1 = ['a',1,'hello',2]
list1 = list()
#列表允许重复值
list1 = list(['a','a','hello'])
#类型转换
list1 = list('hello')
print(list1)
#tuple to list
list1 = list((1,2,'a'))
#获取元素[偏移量]
print(list1[1])
print(list1[-2])
#嵌套列表
list2 = [1,2,'b']
list3 = [list1,list2,1,2]
print(list3)
print(list3[0])
#从左到右,list3[0]获取列表第一个元素,再获取返回列表[2]第二个元素
print(list3[0][2])
#修改元素
list1[1] = 3
print(list3)
#切片提取元素
print(list1[0:2])
print(list1[2:])
print(list1[:-1])
#可以使用step,step<>1
print(list1[::2])
#切片逆序
print(list1[::-1])
#添加元素
list1.append([2,3])
print(list1)
#列表合并
list1 = list1 + list2
print(list1)
list1 += list3
print(list1)
list1.extend(list3)
print(list1)
#列表插入值,参数:(偏移量,插入值)
list1 = [1,2,'a']
list1.insert(0,'b')
print(list1)
#列表删除值
del list1[-1]
del list1[0]
print(list1)
#remove删除指定值
list1.remove(1)
print(list1)
#pop(),删除并返回列表尾元素pop(-1)
#pop(0),删除并返回列表头元素
list1 = [1,2,'a','b']
print(list1.pop(-1))
print(list1)
#查询指定元素位置,偏移量
print(list1.index(2))
#查询指定元素是否存在
print(2 in list1)
#列表指定元素计数
print(list1.count('a'))
#列表转换为字符串
#列表里面所有元素必须为字符串
#list1 = [1,2,'a']
#print(','.join(list1))
#列表转换字符串
list1 = ['a','b','c']
print(','.join(list1))
#字符串转换列表
str1 = ','.join(list1)
print(str1.split(','))
#列表排序
#列表元素必须是同种类型,或者整数浮点混合类型
list1 = ['a','e','b']
#sorted排序返回有序列表,不改变原列表序列
list2 = sorted(list1)
print(list2)
#sort()方法,原列表排序
list1.sort()
print(list1)
#sort(self,key,reverse)
#reverse = True降序排列
list1.sort(reverse = True)
print(list1)
#返回列表长度
print(len(list1))
#列表赋值和copy区别
list1 = [1,2,3]
#赋值
list2 = list1
list1[0] = 'surprise'
#当修改list1值时,list2指向的值也改变
print(list1)
print(list2)
#copy方式
#list2,3,4都是新对象,list1修改时,不影响其他list
list1 = [1,2,3]
list2 = list1.copy()
list3 = list(list1)
list4 = list1[:]
list1[0] = 'surprise'
print(list1)
print(list2)
print(list3)
print(list4)
2.2元组
元组任意类型元素组成序列,元组是不可变的。一旦元组被定义不能进行增加,删除,修改元素操作。
示例1:
#python元组
#创建元组
tuple1 = ()
print(type(tuple1))
#创建的一个或多个元素,以,结尾
tuple1 = 'a',1,2,
print(tuple1)
tuple1 = ('a',1,2)
#元组解包,tuple赋值给多个变量
var1,var2,var3 = tuple1
print(var1,var2,var3)
#tuple进行变量值交换
var1,var2 = var2,var1
print(var1,var2)
#利用tuple()创建元组
tuple1 = tuple(['a',1,2])
#注:元组和列表比较,元组占用空间小,元组值不能修改,元组作为字典值
2.3字典
字典不强调元素顺序性,通过键访问元素。键一般是字符串或其他不可变类型整型,浮点型,元组。字典是可变的,可以增加,删除,修改键值对。
示例1:
#python字典
#创建字典
dict1 = {}
#使用dict()创建字典
#将双值子序列转换为字典
dict1 = dict([['a',1],['b',2],['c',3]])
print(dict1)
dict1 = dict(((1,2),(2,2),(3,4)))
print(dict1)
dict1 = dict([(1,3),(2,5),(3,5)])
print(dict1)
dict1 = dict(('ab','cd','ef'))
print(dict1)
#修改字典值
dict1['a'] = 'hello'
print(dict1)
#添加字典值
dict1['g'] = 'world'
print(dict1)
#合并两个字典
dict2 = dict1
#当被合并字典具有重复的键时,替换合并字典键值
dict1.update(dict2)
print(dict1)
#删除键值
#等号dict1的值地址赋给dict2
del dict2['a']
print(dict1)
#清空字典
dict2.clear()
print(dict1)
#使用in判断元素是否在字典中
dict1 = dict(('ab','cd','ef'))
if 'a' in dict1:
print(dict1['a'])
#使用get方法获取,如果不存在,返回指定值
print(dict1.get('a','not in dict'))
#获取字典所有key值
#python2返回list
#python3返回dict_keys(['a', 'c', 'e'])返回dict_keys类型
print(dict1.keys())
#转换为list
print(list(dict1.keys()))
#获取字典所有value值
print(dict1.values())
print(list(dict1.values()))
#获取字典键值对,元组形式返回
#dict_items([('a', 'b'), ('c', 'd'), ('e', 'f')])
print(dict1.items())
print(list(dict1.items()))
#等号相当于创建一个引用,
#通过copy()复制全新dict
dict2 = dict1.copy()
dict2['a'] = 'hello'
print(dict1,dict2)
2.4集合
集合只剩下键的字典,键与键之间不能重复。集合可以进行交,并,补集运算。
示例1:
#python集合
#创建集合
set1 = set()
set1 = {1,2,'a','c'}
print(set1)
#使用set转换,重复值会去除,无序
set1 = set('hello world')
print(set1)
#列表
set1 = set([1,2,3,5])
print(set1)
#元组
set1 = set((1,1,3,5))
print(set1)
#字典,只会使用key值
set1 = set({'a':1,'b':2,'c':3})
print(set1)
#集合运算
#交集运算
set1 = set('hello')
set2 = set('world')
print(set1 & set2)
#使用intersection
print(set1.intersection(set2))
#并集运算|,union()
print(set1 | set2)
print(set1.union(set2))
#差集运算-,difference()
#只在set1出现,不在第二个set2出现
print(set1 - set2)
print(set1.difference(set2))
#异或,仅在两个集合中出现一次的元素
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
#子集判断
#<=子集
#<真子集
#>=超集,issuperset()
#>真超集
print(set1 <= set2)
print(set1.issubset(set2))
3Python代码结构
Python通过缩进控制代码块结构。
3.1注释及连接符
通过#符号注释代码;
当长代码串需要换行使用\符号连接;
示例:
#使用注释
print('注释') #注释在同一行
#连接符
long_text = 'hello' + \
'world' + \
',welcome'
print(long_text)
3.2判断语句
示例:
#if else语句
#通过缩进判断if和else匹配
if_value = 10
if 5 < if_value < 20 :
print(str(if_value) + '大于5小于20')
if_value = if_value + if_value
#嵌套if
if if_value < 30 :
print(str(if_value) + '小于30')
elif if_value < 40 :
print(str(if_value) + '小于40')
else:
print(str(if_value) + '大于40')
#true or False判断
#布尔 False:null类型,整型0,浮点0.0,空字符串'',空列表[],空元组(),空字典{},空集合set()
set1 = []
if set1 :
print('there is something')
else:
print('there is nothing')
3.3循环语句
Python使用While循环语句
示例1:
#While循环
val_while = 1
while val_while < 5 :
print(str(val_while) + '小于5')
val_while = val_while + 1
#使用break跳出循环
while val_while < 10 :
print(str(val_while) + '小于10')
if val_while < 12 :
break
#使用continue,跳过本次循环
while val_while < 15 :
if val_while == 13 or val_while == 14 :
val_while = val_while + 1
continue
print(str(val_while) + 'continue')
val_while = val_while + 1
#循环外使用else
val_while = 1
while val_while < 2:
if val_while % 2 == 0 :
#如果while循环正常执行完,跳到else
print(val_while)
break
val_while = val_while + 1
else :
print('while else')
Python使用for循环迭代
示例2:
#for循环
#序列对象,通过for快速访问序列元素
#字符串
str1 = 'hi'
for str_item in str1:
print(str_item)
#列表
list1 = ['a',1,2,'b']
for list_item in list1 :
print(list_item)
#字典
dict1 = {'a':1,'b':2}
for dict_val in dict1.values():
print(dict_val)
#返回键值元组形式返回
for dict_item in dict1.items():
print(dict_item)
#break,continue和while中一致
#zip函数
str1 = 'abc'
list2 = ['world','hello',10]
dict1 = { 'dict1': 100, 'dict2':200,'dict3':300 }
for str_item,list_item,dict_value in zip(str1,list2,dict1.values()):
print('string',str_item,'list',list_item,'dict',dict_value)
#使用zip()进行两个序列配对
print(list(zip(str1,list2)))
#将list转换为字典
print(dict( list( zip(str1,list2) ) ))
#range函数
#range(start,stop,step),start默认0,step默认1
#range返回一个可迭代对象
for num1 in range(1,10,-1):
print(num1)
list1 = list(range(0,10,2))
print(list1)
3.4推导式
从一个或多个迭代器快速建立数据结构的方法。Python特有的代码风格。
示例:
#Python推导式
#创建一个列表
list1 = []
list1.append(1)
list1.append(2)
#或者
list1 = []
for num_item in range(1,4):
list1.append(num_item)
#或者
list1 = list(range(1,4))
#列表推导方式
#[expression for item in iterable]
list1 = [num_item for num_item in range(1,4)]
print(list1)
#expession可以是表达式
list1 = [num_item**2 for num_item in range(1,4)]
print(list1)
#可以在推导式中加入条件
#[expression for item in iterable if condition]
#返回1-9偶数序列
list1 = [num_item for num_item in range(1,10) if num_item % 2 == 0]
print(list1)
#使用推导式简化嵌套
list1 = range(1,10)
list2 = range(1,5)
for list1_item in list1:
for list2_item in list2:
print(list1_item,list2_item)
list3 = [(list1_item,list2_item) for list1_item in list1 for list2_item in list2]
print(list3)
#字典推导式
#[key_expression : val_exprssion for expression in iterable]
str1 = 'hello'
#统计字符串个字符出现次数
dict1 = {key1 : str1.count(key1) for key1 in str1}
print(dict1)
#集合推导式
#结构列表推导式一致
set1 = {set1_item for set1_item in range(1,10) if set1_item % 2 == 1}
print(set1)
#元组推导式,没有
#类似使用(),称为生成器
tuple1 = (tuple1_item for tuple1_item in range(1,5))
#返回
#<class 'generator'>
print(type(tuple1))
#<generator object <genexpr> at 0x000001F483821570>
print(tuple1)
#生成器只能遍历一次
for item in tuple1:
print(item)
3.5函数
Python可以将一段逻辑定义为函数,实现代码复用。
函数使用:1定义函数;2调用函数。
一个函数可以接收任何数量参数,返回任何数量结果,默认返回None,调用return 返回任意类型。
示例:
#Python函数
#定义一个空函数
def do_nothing():
pass
#返回none
print(do_nothing())
#定义一个
def return_double(something):
return str(something) + str(something)
#调用返回
print(return_double('hello'))
#关于None,
#None相当于False,
#但是0,0.0,空字符串,空元组,空字典,空列表,空集合相当于False,不等于None
def is_none(something):
if something is None:
print('None')
elif something :
print('True')
else:
print('False')
#参数传递
#位置参数
def param_test(param1,param2,param3):
print({'1':param1,'2':param2,'3':param3 })
#每个参数位置对应,每个参数位置错误,会返回错误结果
param_test('hi','welcome','china')
#关键字参数
#每个参数使用定义时参数名对应,可以不按照定义顺序传参
param_test(param3 = 'china',param2 = 'welcome',param1 = 'hi')
#位置参数和关键字参数混合,首先考虑位置参数
param_test('hi',param2 = 'china',param3 = 'welcom')
#参数默认值
def param_test(param1,param2 = 'default'):
print(param1,param2)
#不传入使用默认参数值
param_test('hi')
param_test('hi','hello')
#使用*,打包位置参数
def param_test(param1,param2,param3,*args):
print(param1,param2,param3,args)
#通过*,实现可变长参数
#输出:1 abc he (2, 3, [1, 2])
param_test('1','abc','he',2,3,[1,2])
#使用**,打包关键字参数
#将关键字参数打包,键位参数名,值为参数值
def param_test(**kwargs):
print(kwargs)
param_test(a = 1,b = 2,c = 3)
#函数文档字符串
#''通过添加函数单行说明
#''''''通过添加函数多行说明
def doc_test():
'文档说明函数'
print('文档说明函数')
def doc_test1():
'''
文档多行说明
'''
print('多行文档说明函数')
doc_test()
doc_test1()
#help()函数查看函数说明
help(doc_test)
#只输出函数说明文档
print(doc_test.__doc__)
print(doc_test1.__doc__)
#函数作为参数
def sum_args(*args):
return sum(*args)
def func_args(func_name,*args):
return func_name(*args)
#调用
print(sum_args((1,3,5)))
print(func_args(sum_args,(1,2,0)))
def add_args(arg1,arg2):
print(arg1+arg2)
def func_add(func,arg1,arg2):
func(arg1,arg2)
func_add(add_args,1,4)
#内部函数
#在函数内部定义函数
def out_func(string_arg):
def in_func(string_arg):
return 'head:' + string_arg
return in_func(string_arg)
print(out_func('hello'))
#闭包:一个被动态创建的,可以记录外部变量的函数
def out_func1(string_arg):
def in_func():
return 'head:' + string_arg
#这里返回内部函数,而不调用
return in_func
func1 = out_func1('hi')
func2 = out_func1('world')
#<function out_func1.<locals>.in_func at 0x000001CD12F7B598>
#<function out_func1.<locals>.in_func at 0x000001CD12F7B620>
print(func1,func2)
print(func1(),func2())
#匿名函数
#lambda表达式
list1 = ['apple','orange','banana']
#将所有首字母大写返回
def lambada_func(word):
return str(word).capitalize()
def call_lambada_func(func,list_arg):
for word in list_arg:
print(func(word))
#调用
call_lambada_func(lambada_func,list1)
#使用lambada表达式实现
call_lambada_func(lambda word : str(word).capitalize(),list1)
#Python函数
#定义一个空函数
def do_nothing():
pass
#返回none
print(do_nothing())
#定义一个
def return_double(something):
return str(something) + str(something)
#调用返回
print(return_double('hello'))
#关于None,
#None相当于False,
#但是0,0.0,空字符串,空元组,空字典,空列表,空集合相当于False,不等于None
def is_none(something):
if something is None:
print('None')
elif something :
print('True')
else:
print('False')
#参数传递
#位置参数
def param_test(param1,param2,param3):
print({'1':param1,'2':param2,'3':param3 })
#每个参数位置对应,每个参数位置错误,会返回错误结果
param_test('hi','welcome','china')
#关键字参数
#每个参数使用定义时参数名对应,可以不按照定义顺序传参
param_test(param3 = 'china',param2 = 'welcome',param1 = 'hi')
#位置参数和关键字参数混合,首先考虑位置参数
param_test('hi',param2 = 'china',param3 = 'welcom')
#参数默认值
def param_test(param1,param2 = 'default'):
print(param1,param2)
#不传入使用默认参数值
param_test('hi')
param_test('hi','hello')
#使用*,打包位置参数
def param_test(param1,param2,param3,*args):
print(param1,param2,param3,args)
#通过*,实现可变长参数
#输出:1 abc he (2, 3, [1, 2])
param_test('1','abc','he',2,3,[1,2])
#使用**,打包关键字参数
#将关键字参数打包,键位参数名,值为参数值
def param_test(**kwargs):
print(kwargs)
param_test(a = 1,b = 2,c = 3)
#函数文档字符串
#''通过添加函数单行说明
#''''''通过添加函数多行说明
def doc_test():
'文档说明函数'
print('文档说明函数')
def doc_test1():
'''
文档多行说明
'''
print('多行文档说明函数')
doc_test()
doc_test1()
#help()函数查看函数说明
help(doc_test)
#只输出函数说明文档
print(doc_test.__doc__)
print(doc_test1.__doc__)
#函数作为参数
def sum_args(*args):
return sum(*args)
def func_args(func_name,*args):
return func_name(*args)
#调用
print(sum_args((1,3,5)))
print(func_args(sum_args,(1,2,0)))
def add_args(arg1,arg2):
print(arg1+arg2)
def func_add(func,arg1,arg2):
func(arg1,arg2)
func_add(add_args,1,4)
#内部函数
#在函数内部定义函数
def out_func(string_arg):
def in_func(string_arg):
return 'head:' + string_arg
return in_func(string_arg)
print(out_func('hello'))
#闭包:一个被动态创建的,可以记录外部变量的函数
def out_func1(string_arg):
def in_func():
return 'head:' + string_arg
#这里返回内部函数,而不调用
return in_func
func1 = out_func1('hi')
func2 = out_func1('world')
#<function out_func1.<locals>.in_func at 0x000001CD12F7B598>
#<function out_func1.<locals>.in_func at 0x000001CD12F7B620>
print(func1,func2)
print(func1(),func2())
#匿名函数
#lambda表达式
list1 = ['apple','orange','banana']
#将所有首字母大写返回
def lambada_func(word):
return str(word).capitalize()
def call_lambada_func(func,list_arg):
for word in list_arg:
print(func(word))
#调用
call_lambada_func(lambada_func,list1)
#使用lambada表达式实现
call_lambada_func(lambda word : str(word).capitalize(),list1)
3.6生成器
生成器用来生成Python序列。通过迭代创建序列,不需要在内存创建存储整个序列。
示例:
#Python生成器
#自定义range,
def my_range(start = 0,stop = 10,step = 1):
number = start
while number < stop:
yield number
number += step
#返回一个生成器对象
range1 = my_range(1,20)
#生成器对象<generator object my_range at 0x0000022536231ED0>
print(range1)
#使用for循环
for item in range1:
print(item)
#生成器再次遍历,不会再次输出值
for item in range1:
print(item)
3.7装饰器
使用装饰器,对原有函数添加新的功能
示例:
#Python装饰器
#两个数相加
def add_num(a,b):
return a + b
#装饰函数
def docu_func(func):
def new_func(*args,**kwargs):
print('function name',func.__name__)
print('function arg',args)
print('function kwargs',kwargs)
result = func(*args,**kwargs)
print('function result',result)
return result
return new_func
#装饰函数使用
call_docu_func = docu_func(add_num)
#当调用时,如果参数多于被装饰函数定义,报错
print('手动装饰器',call_docu_func(1,2))
#直接在函数定义时添加装饰器
@docu_func
def add_num1(a,b):
return a + b
#调用
print('定义时添加装饰器',add_num1(1,2))
#多个装饰器
def docu_func1(func):
def new_func(*args,**kwargs):
print('function name',func.__name__)
print('function arg',args)
print('function kwargs',kwargs)
result = func(*args,**kwargs)
print('function result',result)
return result * result
return new_func
#调整装饰器顺序返回结果一致,靠近定义的装饰器先执行
#使用多个装饰器1
@docu_func
@docu_func1
def add_num1(a,b):
return a + b
print('多个装饰器1',add_num1(1,2))
#使用多个装饰器2
@docu_func1
@docu_func
def add_num1(a,b):
return a + b
print('多个装饰器2',add_num1(1,2))
3.8命名空间和作用域
变量命名空间和作用域
示例:
#Python命名空间和作用域
#全局变量
name_space = 'hi'
print(name_space,id(name_space))
def name_space_func():
#这里name_space报错,因为没定义
#print(name_space)
#当在函数内部不能修改全局变量
#这里是函数内部的name_space
name_space = 'hello'
#使用id,变量id
print(name_space,id(name_space))
# 使用local返回局部命名空间字典
print('局部变量',locals().get('name_space'))
#调用函数
name_space_func()
#使用globals返回全局命名空间字典
print('全局变量',globals().get('name_space'))
#使用全局变量
def name_space_func1():
#使用全局变量
global name_space
print('name_space_func1',name_space,id(name_space))
name_space = 'hello'
print('name_space_func1',name_space,id(name_space))
#修改global变量?这里的name_space是新的id
name_space = 'hi world'
print('name_space_func1',name_space,id(name_space))
name_space_func1()
#名称中的_,__这些开头变量,是Python的变量
#__main__:主程序
print(globals().get('__main__'))
3.9异常
示例:
#Python异常
list1 = [1,5,7]
pos = 5
#出现异常IndexError: list index out of range
#print(list1[pos])
#捕捉处理异常
try:
print(list1[pos])
except:
print('pos outer 0 -',len(list1)-1)
#可以使用except捕捉所有异常,也可以分类捕捉异常
try:
print(1/0)
except IndexError as err:
print('error index',pos)
except Exception as other:
print('other exception')
#自定义异常
class my_exception(Exception):
print('my_exception')
try:
#抛出异常
raise my_exception
except my_exception as err:
print('自定义exception')