赞
踩
# 注释内容
"""
第一⾏行行注释
第二⾏行行注释
第三⾏行行注释
"""
'''
注释1
注释2
注释3
'''
变量名 = 值
格式符号 | 转换 |
---|---|
%s | 字符串 |
%d | 有符号的十进制整数 |
%f | 浮点数 |
%c | 字符 |
%u | 无符号十进制整数 |
%o | 八进制整数 |
%x | 十六进制整数(小写ox) |
%X | 十六进制整数(大写OX) |
%e | 科学计数法(小写’e’) |
%E | 科学计数法(大写‘E’) |
%g | %f 和 %e 的简写 |
%G | %f 和 %E 的简写 |
格式化字符串除了%s
,还可以写为f'{表达式}'
age = 18; name = 'Tom' weight = 75.5 student_id = 1 # 我的名字是TOM print('我的名字是%s' % name) # 我的学号是0001 print('我的学号是%4d' % student_id) # 我的体重是75.50公⽄ print('我的体重是%.2f公斤' % weight) # 我的名字是TOM,今年18岁了 print('我的名字是%s,今年%d岁了' % (name,age)) # 我的名字是TOM,今年19岁了 print('我的名字是%s,今年%d岁了' % (name,age+1)) # 我的名字是TOM,明年19岁了 print(f'我的名字是{name},明年{age+1}岁了')
转义字符
\n
:换行
\t
:制表符
结束符
想⼀想,为什么两个print会换行输出?
print('输出的内容',end='\n')
在Python中, print(), 默认自带 end="\n"
这个换行结束符,所以导致每两个 print 直接会换⾏展示,用户可以按需求更改结束符。
input("提示信息")
password = input("请输入密码:")
print(f'{您输入的密码是{password}}')
#<class 'str'>
print(type(password))
函数 | 说明 |
---|---|
int(x,[,base]) | 将x转换为一个整数 |
float(x) | 将x转换为一个浮点数 |
complex(real [,imag]) | 创建一个是复数,real为实部,imag为虚部 |
str(x) | 将对象x转换为字符串 |
repr(x) | 将对象x转换为表达式字符串 |
eval(str) | 用来计算在字符串中的有效Python表达式,并返回一个对象 |
tuple(s) | 将序列s转换为一个元组 |
list(s) | 将序列s转换为一个列表 |
chr(x) | 将一个整数转换为一个Unicode字符 |
ord(x) | 将一个字符串转换为它的ASCII整数值 |
hex(x) | 将一个整数转换为一个十六进制字符串 |
oct(x) | 将一个整数转换为一个八进制字符串 |
bin(x) | 将一个整数转换为一个二进制字符串 |
#1.接收用户输入
num = input('请输入幸运数字:')
#2.打印结果
print(f"您的幸运数字是{num}")
#3.检测接收到的用户输入的数据类型-str
print(type(num))
#4.转换数据类型为整型-int
print(type(int(num)))
()
**
指数
*
/
//
整除
%
+
-
=
+=
-=
*=
/=
//=
%=
**=
==
!=
>
<
>=
<=
and
or
not
if
age = int(input('请输⼊您的年年龄: '))
if age >= 18:
print(f'您的年龄是{age},已经成年,可以上网')
print('系统关闭')
if...else...
age = int(input('请输入您的年龄: '))
if age >= 18:
print(f'您的年龄是{age},已经成年,可以上网')
else:
print(f'您的年龄是{age},未成年,请自行回家写作业')
print('系统关闭')
多重判断
age = int(input('请输⼊您的年龄: '))
if age < 18:
print(f'您的年龄是{age},童工⼀一枚')
elif age >= 18 and age <= 60:
print(f'您的年龄是{age},合法工龄')
elif age > 60:
print(f'您的年龄是{age},可以退休')
if嵌套
""" 1. 如果有钱,则可以上车 2. 上车后,如果有空座,可以坐下 上车后,如果没有空座,则站着等空座位 如果没钱,不能上⻋车 """ # 假设⽤ money = 1 表示有钱, money = 0表示没有钱; seat = 1 表示有空座, seat = 0 表示没有空座 money = 1 seat = 0 if money == 1: print('土豪,不差钱,顺利上车') if seat == 1: print('有空座,可以坐下') else: print('没有空座,站等') else: print('没钱,不能上⻋,追着公交车跑')
三目运算符
条件成立执行的表达式 if 条件 else 条件不成立执行的表达式
a = 1
b = 2
c = a if a>b else b
print(c)
i = 1
result = 0
while i <= 100:
result += i
i += 1
# 输出5050
print(result)
break
i = 1
while i <= 5:
if i == 4:
print(f'吃饱了不吃了')
break
print(f'吃了第{i}个苹果')
i += 1
continue
i = 1
while i <= 5:
if i == 3:
print(f'⼤大⾍虫⼦子,第{i}个不不吃了了')
# 在continue之前⼀一定要修改计数器器,否则会陷⼊入死循环
i += 1
continue
print(f'吃了第{i}个苹果')
i += 1
嵌套
# 重复打印9行表达式
j = 1
while j <= 9:
# 打印⼀一⾏行行⾥里里⾯面的表达式 a * b = a*b
i = 1
while i <= j:
print(f'{i}*{j}={j*i}', end='\t')
i += 1
print()
j += 1
else
i = 1
while i <= 5:
print('媳妇儿,我错了')
i += 1
else:
print('媳妇原谅我了,真开心,哈哈哈')
str1 = 'itheima'
for i in str1:
print(i)
break
str1 = 'itheima'
for i in str1:
if i == 'e':
print('遇到e不不打印')
break
print(i)
continue
str1 = 'itheima'
for i in str1:
if i == 'e':
print('遇到e不不打印')
continue
print(i)
else
str1 = 'itheima'
for i in str1:
print(i)
else:
print('循环正常结束之后执行的代码')
三引号形式的字符串支持换行
name1 = 'Tom'
name2 = "Rose"
a = '''i am Tom,
nice to meet you! '''
name = input('请输⼊入您的名字: ')
print(f'您输⼊入的名字是{name}')
print(type(name))
password = input('请输⼊入您的密码: ')
print(f'您输⼊入的密码是{password}')
print(type(password))
索引
name = "abcdef"
print(name[1]) # b
print(name[0]) # a
print(name[2]) # c
序列[开始位置下标:结束位置下标:步长]
name = "abcdefg";
print(name[2:5:1]) #cde
print(name[2:5]) #cde
print(name[:5]) #abcde
print(name[1:]) #bcdefg
print(name[:]) #abcdefg
print(name[::2]) #aceg
print(name[:-1]) #abcdef,-1表示倒数第一个数据
print(name[-4:-1]) #def
print(name[::-1]) #gfedcba
字符串序列.find(子串,开始位置下标,结束位置下标)
返回子串开始位置的下标,否则返回-1
mystr = "hello world and itcast and itheima and Python"
print(mystr.find('and')) # 12
print(mystr.find('and', 15, 30)) # 23
print(mystr.find('ands')) # -1
字符串序列.index(子串,开始位置下标,结束位置下标)
返回子串开始位置的下标,否则报异常
mystr = "hello world and itcast and itheima and Python"
print(mystr.index('and')) # 12
print(mystr.index('and', 15, 30)) # 23
print(mystr.index('ands')) # 报错
字符串序列.count(子串,开始位置下标,结束位置下标)
mystr = "hello world and itcast and itheima and Python"
print(mystr.count('and')) # 3
print(mystr.count('ands')) # 0
print(mystr.count('and', 0, 20)) # 1
字符串序列.replace(旧子串,新子串,替换次数)
mystr = "hello world and itcast and itheima and Python"
# 结果: hello world he itcast he itheima he Python
print(mystr.replace('and', 'he'))
# 结果: hello world he itcast he itheima he Python
print(mystr.replace('and', 'he', 10))
# 结果: hello world and itcast and itheima and Python
print(mystr)
字符串序列.split(分隔字符,num)
mystr = "hello world and itcast and itheima and Python"
# 结果: ['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr.split('and'))
# 结果: ['hello world ', ' itcast ', ' itheima and Python']
print(mystr.split('and', 2))
# 结果: ['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
print(mystr.split(' '))
# 结果: ['hello', 'world', 'and itcast and itheima and Python']
print(mystr.split(' ', 2))
字符或子串.join(多字符串组成的序列)
list1 = ['chuan', 'zhi', 'bo', 'ke']
t1 = ('aa', 'b', 'cc', 'ddd')
# 结果: chuan_zhi_bo_ke
print('_'.join(list1))
# 结果: aa...b...cc...ddd
print('...'.join(t1))
将字符串第一个字符转换成大写
capitalize()函数转换后,只有字符串第一个字符大写,其他的字符全都小写
mystr = "hello world and itcast and itheima and Python"
# 结果: Hello world and itcast and itheima and python
print(mystr.capitalize())
将字符串每个单词首字母转换成大写
mystr = "hello world and itcast and itheima and Python"
# 结果: Hello World And Itcast And Itheima And Python
print(mystr.title())
将字符串中大写转小写
mystr = "hello world and itcast and itheima and Python"
# 结果: hello world and itcast and itheima and python
print(mystr.lower())
将字符串中小写转大写
mystr = "hello world and itcast and itheima and Python"
# 结果: HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON
print(mystr.upper())
删除字符串左、右、两侧空白字符
mystr = " hello world "
# "hello world "
print(mystr.lstrip())
# " hello world"
print(mystr.rstrip())
# "hello world"
print(mystr.strip())
左对齐、右对齐、居中对齐,并指定字符填充值至对应长度
字符串序列.ljust(长度,填充字符)
mystr = 'hello'
# 'hello.....'
print(mystr.ljust(10,'.'))
# 'hello '
print(mystr.ljust(10))
# ' hello '
print(mystr.center(10))
# '..hello...'
print(mystr.center(10,'.'))
字符串序列.startswith(子串, 开始位置下标, 结束位置下标)
检查字符串是否是以指定⼦子串开头,是则返回 True,否则返回 False。
mystr = "hello world and itcast and itheima and Python "
# 结果: True
print(mystr.startswith('hello'))
# 结果False
print(mystr.startswith('hello', 5, 20))
字符串序列.endswith(子串, 开始位置下标, 结束位置下标)
检查字符串是否是以指定子串结尾,是则返回 True,否则返回 False。
mystr = "hello world and itcast and itheima and Python"
# 结果: True
print(mystr.endswith('Python'))
# 结果: False
print(mystr.endswith('python'))
# 结果: False
print(mystr.endswith('Python', 2, 20))
如果字符串至少有⼀个字符并且所有字符都是字母则返回 True, 否则返回 False。
mystr1 = 'hello'
mystr2 = 'hello12345'
# 结果: True
print(mystr1.isalpha())
# 结果: False
print(mystr2.isalpha())
如果字符串只包含数字则返回 True 否则返回 False。
mystr1 = 'aaa12345'
mystr2 = '12345'
# 结果: False
print(mystr1.isdigit())
# 结果: False
print(mystr2.isdigit())
如果字符串至少有⼀个字符并且所有字符都是字母或数字则返回 True,否则返回False。
mystr1 = 'aaa12345'
mystr2 = '12345-'
# 结果: True
print(mystr1.isalnum())
# 结果: False
print(mystr2.isalnum())
如果字符串中只包含空白,则返回 True,否则返回 False。
mystr1 = '1 2 3 4 5'
mystr2 = ' '
# 结果: False
print(mystr1.isspace())
# 结果: True
print(mystr2.isspace())
列表中数据允许修改
[数据1,数据2,数据3,数据4....]
name_list = ['Tom','Lily','Rose']
print(name_list[0])
print(name_list[1])
print(name_list[2])
列表序列.index(数据,开始位置下标,结束位置下标)
返回指定数据所在位置的下标
count()
统计指定数据在当前列表中出现的次数
len()
访问列表长度
name_list = ['Tom','Lily','Rose']
print(name_list.index('Lily',0,2)) #1
print(name_list.count('Lily')) #1
print(len(name_list)) #3
in
判断指定数据在某个列表序列,在返回True,否则返回False
not in
:判断指定数据不在某个列表序列,如果不在返回True,否则返回False
name_list = ['Tom', 'Lily', 'Rose']
# 结果: True
print('Lily' in name_list)
# 结果: False
print('Lilys' in name_list)
列表序列.append(数据)
name_list = ['Tom', 'Lily', 'Rose']
name_list.append('xiaoming')
# 结果: ['Tom', 'Lily', 'Rose', 'xiaoming']
print(name_list
如果append()追加的数据是一个序列,则追加整个序列到列表
name_list = ['Tom', 'Lily', 'Rose']
name_list.append(['xiaoming', 'xiaohong'])
# 结果: ['Tom', 'Lily', 'Rose', ['xiaoming', 'xiaohong']]
print(name_list)
extend()列表结尾追加数据,如果数据是⼀个序列,则将这个序列的数据逐⼀添加到列表。
列表序列.extend(数据)
name_list = ['Tom', 'Lily', 'Rose']
name_list.extend('xiaoming')
# 结果: ['Tom', 'Lily', 'Rose', 'x', 'i', 'a', 'o', 'm', 'i', 'n', 'g']
print(name_list)
name_list = ['Tom', 'Lily', 'Rose']
name_list.extend(['xiaoming', 'xiaohong'])
# 结果: ['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaohong']
print(name_list)
指定位置新增数据
列表序列。insert(位置下标,数据)
、
name_list = ['Tom', 'Lily', 'Rose']
name_list.insert(1, 'xiaoming')
# 结果: ['Tom', 'xiaoming', 'Lily', 'Rose']
print(name_list)
del 目标
name_list = ['Tom', 'Lily', 'Rose']
# 结果:报错提示: name 'name_list' is not defined
del name_list
print(name_list)
name_list = ['Tom', 'Lily', 'Rose']
del name_list[0]
# 结果: ['Lily', 'Rose']
print(name_list)
删除指定下标的数据(默认为最后一个),并返回该数据。
name_list = ['Tom', 'Lily', 'Rose']
del_name = name_list.pop(1)
# 结果: Lily
print(del_name)
# 结果: ['Tom', 'Rose']
print(name_list)
移除列表中某个数据的第⼀个匹配项。
name_list = ['Tom', 'Lily', 'Rose']
name_list.remove('Rose')
# 结果: ['Tom', 'Lily']
print(name_list)
name_list = ['Tom', 'Lily', 'Rose']
name_list.clear()
print(name_list) # 结果: []
name_list = ['Tom', 'Lily', 'Rose']
name_list[0] = 'aaa'
# 结果: ['aaa', 'Lily', 'Rose']
print(name_list)
reverse()
num_list = [1, 5, 2, 3, 6, 8]
num_list.reverse()
# 结果: [8, 6, 3, 2, 5, 1]
print(num_list)
列表序列.sort( key=None, reverse=False)
True – 降序 ; False – 升序
num_list = [1, 5, 2, 3, 6, 8]
num_list.sort()
# 结果: [1, 2, 3, 5, 6, 8]
print(num_list)
name_list = ['Tom', 'Lily', 'Rose']
name_li2 = name_list.copy()
# 结果: ['Tom', 'Lily', 'Rose']
print(name_li2)
name_list = ['Tom','Lily','Rose']
i = 0
while i < len(name_list):
print(name_list[i])
i+=1
name_list = ['Tom', 'Lily', 'Rose']
for i in name_list:
print(i)
name_list = [['⼩小明', '⼩小红', '⼩小绿'], ['Tom', 'Lily', 'Rose'], ['张三', '李李四', '王五']
# 第⼀步:按下标查找到李四所在的列表
print(name_list[2])
# 第⼆步:从李四所在的列表里面,再按下标找到数据李四
print(name_list[2][1])
一个元组可以存储多个数据,元组内的数据是不能修改的
元组特点:定义元组使用小括号,且逗号隔开各个数据,数据可以是不同的数据类型
# 多个数据元组
t1 = (10,20,30)
# 单个数据元组
t2 = (10,)
注意:如果定义的元组只有⼀个数据,那么这个数据后面也好添加逗号,否则数据类型为唯一的这个数据的数据类型
t2 = (10,)
print(type(t2)) # tuple
t3 = (20)
print(type(t3)) # int
t4 = ('hello')
print(type(t4)) # str
按下标查找
tuple1 = ('aa', 'bb','cc','dd')
print(tuple1[0]) # aa
index()
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.index('aa')) # 0
count()
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.count('bb')) # 2
len()
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(len(tuple1)) # 4
注意:元组内的直接数据如果修改则立即报错
tuple1 = ('aa', 'bb', 'cc', 'bb')
tuple1[0] = 'aaa'
但是如果元组里面有列表,修改列表里面的数据则是支持的,故自觉很重要。
tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30)
print(tuple2[2]) # 访问到列表
# 结果: (10, 20, ['aaaaa', 'bb', 'cc'], 50, 30)
tuple2[2][0] = 'aaaaa'
print(tuple2)
创建集合使用 {}
或 set()
, 但是如果要创建空集合只能使用 set() ,因为 {} 用来创建空字典。
s1 = {10, 20, 30, 40, 50}
print(s1) # {40, 10, 50, 20, 30}
s2 = {10, 30, 20, 10, 30, 40, 30, 50}
print(s2) # {40, 10, 50, 20, 30}
s3 = set('abcdefg')
print(s3) # {'c','g','b','f','a','d','e'}
s4 = set()
print(type(s4)) # set
s5 = {}
print(type(s5)) # dict
add()
s1 = {10, 20}
s1.add(100)
s1.add(10)
print(s1) # {100, 10, 20}
update()
追加的数据是序列
s1 = {10, 20}
# s1.update(100) # 报错
s1.update([100, 200])
s1.update('abc')
print(s1) #{'a',100,200,10,'b','c',20}
remove()
删除集合中的指定数据,如果数据不存在则报错。
s1 = {10, 20}
s1.remove(10)
print(s1)
s1.remove(10) # 报错
print(s1)
discard()
删除集合中的指定数据,如果数据不存在也不会报错。
s1 = {10, 20}
s1.discard(10)
print(s1)
s1.discard(10)
print(s1)
pop()
随机删除集合中的某个数据,并返回这个数据
s1 = {10, 20, 30, 40, 50}
del_num = s1.pop()
print(del_num)
print(s1)
in
not in
s1 = {10, 20, 30, 40, 50}
print(10 in s1)
print(10 not in s1)
#有数据字典
dict1 = {'name':'Tom','age':20,'gender':'男'}
#空字典
dict2 = {};
dict3 = dict();
字典序列[key] = 值
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
dict1['name'] = 'Rose'
# 结果: {'name': 'Rose', 'age': 20, 'gender': '男'}
print(dict1)
dict1['id'] = 110
# {'name': 'Rose', 'age': 20, 'gender': '男', 'id': 110}
print(dict1
del()/del
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
del dict1['gender']
# 结果: {'name': 'Tom', 'age': 20}
print(dict1
clear()
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
dict1.clear()
print(dict1) # {}
字典序列[key] = 值
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1['name']) # Tom
print(dict1['id']) # 报错
字典序列.get(key,默认值)
如果当前查找的key不存在则返回第二个参数,如果省略第二个参数,则返回None
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1.get('name')) # Tom
print(dict1.get('id', 110)) # 110
print(dict1.get('id')) # None
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1.keys()) # dict_keys(['name', 'age', 'gender'])
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1.values()) # dict_values(['Tom', 20, '男'])
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1.items()) # dict_items([('name', 'Tom'), ('age', 20), ('gender',
'男')])
dict1 = {'name':'Tom','age':20,'gender':'男'}
for key in dict1.keys():
print(key)
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
for value in dict1.values():
print(value)
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
for item in dict1.items():
print(item)
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
for key, value in dict1.items():
print(f'{key} = {value}')
运算符 | 描述 | 支持的容器类型 |
---|---|---|
+ | 合并 | 字符串、列表、元组 |
* | 复制 | 字符串、列表、元组 |
in | 元素是否存在 | 字符串、列表、元组、字典 |
not in | 元素是否不存在 | 字符串、列表、元组、字典 |
+
#1.字符串 str1 = 'aa' str2 = 'bb' str3 = str1 + str2 print(str3) #aabb #2.列表 list1 = [1,2] list2 = [10,20] list3 = list1 + list2 print(list3) #[1,2,10,20] #3.元组 t1 = (1,2) t2 = (10,20) t3 = t1 + t2 print(t3) #(1,2,10,20)
*
# 1. 字符串
print('-' * 10) # ----------
# 2. 列表
list1 = ['hello']
print(list1 * 4) # ['hello', 'hello', 'hello', 'hello']
# 3. 元组
t1 = ('world',)
print(t1 * 4) # ('world', 'world', 'world', 'world')
in 或 not in
# 1. 字符串
print('a' in 'abcd') # True
print('a' not in 'abcd') # False
# 2. 列表
list1 = ['a', 'b', 'c', 'd']
print('a' in list1) # True
print('a' not in list1) # False
# 3. 元组
t1 = ('a', 'b', 'c', 'd')
print('aa' in t1) # False
print('aa' not in t1) # True
函数 | 描述 |
---|---|
len() | 计算容器中元素个数 |
del 或 del() | 删除 |
max() | 返回容器中元素最大值 |
min() | 返回容器中元素最小值 |
range(start,end,step) | 生成从start到end的数字,步长为step,供for循环使用 |
enumerate() | 函数用于将⼀个可遍历的数据对象(如列表、元组或字符串)组合为⼀个索引序列,同时列出数据和数据下标,⼀般用在 for 循环当中。 |
len()
# 1. 字符串
str1 = 'abcdefg'
print(len(str1)) # 7
# 2. 列表
list1 = [10, 20, 30, 40]
print(len(list1)) # 4
# 3. 元组
t1 = (10, 20, 30, 40, 50)
print(len(t1)) # 5
# 4. 集合
s1 = {10, 20, 30}
print(len(s1)) # 3
# 5. 字典
dict1 = {'name': 'Rose', 'age': 18}
print(len(dict1)) # 2
del()
# 1. 字符串
str1 = 'abcdefg'
del str1
print(str1)
# 2. 列表
list1 = [10, 20, 30, 40]
del(list1[0])
print(list1) # [20, 30, 40]
max()
# 1. 字符串
str1 = 'abcdefg'
print(max(str1)) # g
# 2. 列表
list1 = [10, 20, 30, 40]
print(max(list1)) # 40
min()
# 1. 字符串
str1 = 'abcdefg'
print(min(str1)) # a
# 2. 列表
list1 = [10, 20, 30, 40]
print(min(list1)) # 10
range()
# 1 2 3 4 5 6 7 8 9
for i in range(1, 10, 1):
print(i)
# 1 3 5 7 9
for i in range(1, 10, 2):
print(i)
# 0 1 2 3 4 5 6 7 8 9
for i in range(10):
print(i)
enumerate(可遍历对象,start=0)
list1 = ['a', 'b', 'c', 'd', 'e']
for i in enumerate(list1):
print(i) #(0,'a') (1,'b') (2,'c') (3,'d') (4,'e')
for index, char in enumerate(list1, start=1):
print(f'下标是{index}, 对应的字符是{char}')
元组tuple()
list1 = [10, 20, 30, 40, 50, 20]
s1 = {100, 200, 300, 400, 500}
print(tuple(list1))
print(tuple(s1))
列表list()
t1 = ('a', 'b', 'c', 'd', 'e')
s1 = {100, 200, 300, 400, 500}
print(list(t1))
print(list(s1))
集合set()
list1 = [10, 20, 30, 40, 50, 20]
t1 = ('a', 'b', 'c', 'd', 'e')
print(set(list1))
print(set(t1))
# 1. 准备⼀个空列列表
list1 = []
# 2. 书写循环,依次追加数字到空列表list1中
i = 0
while i < 10:
list1.append(i)
i += 1
print(list1)
list1 = []
for i in range(10):
list1.append(i)
print(list1
列表推导式
list1 = [i for i in range(10)]
print(list1)
list1 = [i for i in range(0,10,2)]
print(list1)
list1 = [i for i in range(10) if i % 2 == 0]
print(list1)
list1= [(i,j) for i in range(1,3) for j in range(3)]
print(list1) # [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
dict1 = {i:i**2 for i in range(1,5)}
print(dict1) #{1:1,2:4,3:9,4:16}
list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']
dict1 = {list1[i]:list2[i] for i in range(len(list1))}
print(dict1)
counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
# 需求:提取上述电脑数量量⼤于等于200的字典数据
count1 = {key:value for key, value in counts.items() if value >= 200}
print(count1) #{'MBP':268,'DELL':201}
list1 = [1,1,2]
set1 = {i**2 for i in list1}
print(set1) #{1,4}
先定义后使用
def 函数名(参数):
代码1
代码2
.....
函数名(参数)
# 定义函数时同时定义了接收用户数据的参数a和b, a和b是形参
def add_num(a,b):
result = a + b
print(result)
# 调⽤用函数时传⼊了真实的数据10 和 20,真实数据为实参
add_num(10,20)
def sum_num(a,b):
return a + b
#用result变量保存函数返回值
result = sum_num(1,2)
print(result)
函数返回多个数据时,默认是元组类型
def return_num():
return 1, 2
result = return_num()
print(result) # (1, 2)
def 函数名(参数):
"""说明文档的位置"""
代码
......
def sum_num(a,b):
"""求和函数"""
return a + b
help(sum_num)
def testB():
print('----testB start----')
print('执行代码')
print('----testB end----')
def testA():
print('---- testA start----')
testB()
print('---- testA end----')
testA()
局部变量和全局变量
a = 100
def testA():
print(a)
def testB():
# global 关键字声明a是全局变量
global a
a = 200
print(a)
testA() # 100
testB() # 200
print(f'全局变量a = {a}') # 全局变量a = 200
调用函数时根据函数定义的参数位置来传递参数
def user_info(name, age, gender):
print(f'您的名字是{name}, 年年龄是{age}, 性别是{gender}')
user_info('TOM', 20, '男')
def user_info(name, age, gender):
print(f'您的名字是{name}, 年龄是{age}, 性别是{gender}')
user_info('Rose', age=20, gender='女')
user_info('⼩明', gender='男', age=16)
def user_info(name, age, gender='男'):
print(f'您的名字是{name}, 年龄是{age}, 性别是{gender}')
user_info('TOM', 20)
user_info('Rose', 18, '女')
传进的所有参数都会被args变量收集,它会根据传进参数的位置合并为⼀个元组(tuple),args是元组类型,这就是包裹位置传递。
包裹位置传递
def user_info(*args):
print(args)
#('TOM',)
user_info('TOM')
#('TOM',18)
user_info('TOM',18)
包裹关键词传递
def user_info(**kwargs):
print(kwargs)
# {'name': 'TOM', 'age': 18, 'id': 110}
user_info(name='TOM', age=18, id=110)
拆包元组
def return_num()
return 100,200
num1, num2 = return_num();
print(num1) #100
print(num2) #200
拆包字典
dict1 = {'name':'Tom', 'age':18}
a, b = dict1;
# 对字典进行拆包,取出来的是字典的key
print(a) #name
print(b) #age
print(dict1[a]) #Tom
print(dict1[b]) #18
# 1. 定义中间变量量
c = 0
# 2. 将a的数据存储到c
c = a
# 3. 将b的数据20赋值到a,此时a = 20
a = b
# 4. 将之前c的数据10赋值到b,此时b = 10
b = c
print(a) # 20
print(b) # 10
a, b =1, 2
a, b = b, a
print(a) #2
print(b) #1
我们可以⽤id()
来判断两个变量是否为同⼀个值的引用。
# 1. int 类型 a = 1 b = a print(b) #1 print(id(a)) # 140708464157520 print(id(b)) # 140708464157520 a = 2 print(b) # 1,说明int类型为不可变类型 print(id(a)) # 140708464157552,此时得到是的数据2的内存地址 print(id(b)) # 140708464157520 # 2. 列表 aa = [10, 20] bb = aa print(id(aa)) # 2325297783432 print(id(bb)) # 2325297783432 aa.append(30) print(bb) # [10, 20, 30], 列表为可变类型 print(id(aa)) # 2325297783432 print(id(bb)) # 2325297783432
def test1(a):
print(a)
print(id(a))
a += a
print(a)
print(id(a))
# int:计算前后id值不同
b = 100
test1(b)
# 列表:计算前后id值相同
c = [11, 22]
test1(c)
# 3+2+1
def sum_numbers(num):
#1.如果是1,直接返回1
if num == 1:
return 1
#2.如果不是1,重复执行累加
result = num + sum_numbers(num-1)
#3.返回累加结果
sum_result = sum_numbers(3)
#输出结果为6
print(sum_result)
lambda 参数列表 : 表达式
#函数
def fn1():
return 200
print(fn1)
print(fn1())
fn2 = lambda : 100
print(fn2)
print(fn2())
def add(a,b):
return a+b
result = add(1,2)
print(result)
print((lambda a,b:a+b)(1,2))
print((lambda:100)())
print((lambda a:a)('hello world'))
print((lambda a,b,c=100 : a+b+c)(10,20))
print((lambda *args:args)(10,20,30))
print((lambda **kwargs:kwargs)(name='python',age=20))
print((lambda a,b : a if a > b else b)(1000, 500))
students = [ {'name': 'TOM', 'age': 20}, {'name': 'ROSE', 'age': 19}, {'name': 'Jack', 'age': 22} ] #按name值升序排列 students.sort(key=lambda x : x['name']) print(students) # 按name值降序排列 students.sort(key=lambda x: x['name'], reverse=True) print(students) # 按age值升序排列 students.sort(key=lambda x: x['age']) print(students)
把函数作为参数传入
def add_num(a, b):
return abs(a) + abs(b)
result = add_num(-1, 2)
print(result) # 3
def sum_num(a, b, f):
return f(a) + f(b)
result = sum_num(-1, 2, abs)
print(result) # 3
map(func, lst)
,将传入的函数变量func作用到lst变量的每个元素中,并将结果组成新的列表(Python2)/迭代器(Python3)返回。
list1 = [1,2,3,4,5]
def func(x):
return x**2
result = map(func,list1)
print(result) # <map object at 0x0000013769653198>
print(list(result)) #[1,4,9,16,25]
reduce(func(x,y),lst)
,其中func必须有两个参数。每次func计算的结果继续和序列的下一个元素做累积计算。
import functools
list1 = [1,2,3,4,5]
def func(a,b):
return a + b
result = functools.reduce(func,list1)
print(result) #15
filter(func, lst)
函数用于过滤序列, 过滤掉不符合条件的元素, 返回⼀个 filter 对象,。如果要转换为列表,可以使用 list() 来转换。
list1 = [1,2,3,4,5,6,7,8,9,10]
def func(x):
return x % 2 ==0
result = filter(func, list1)
print(result) # <filter object at 0x0000017AF9DC3198>
print(list(result)) # [2, 4, 6, 8, 10]
open(name, mode)
文件对象.close()
文件对象.write('内容')
# 1. 打开⽂件
f = open('test.txt', 'w')
# 2.⽂件写入
f.write('hello world')
# 3. 关闭文件
f.close()
文件对象.read(num)
num是从文件中读取的数据的长度(字节),没有就是全部
readlines()
按照行的方式把整个文件中的内容进行⼀次性读取,并且返回的是⼀个列表,其中每⼀行的数据为⼀个元素。
f = open('test.txt')
content = f.readlines()
# ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc']
print(content)
# 关闭文件
f.close()
readline()
一次读取一行内容
f = open('test.txt')
content = f.readline()
print(f'第⼀行: {content}')
content = f.readline()
print(f'第⼆行: {content}')
# 关闭⽂文件
f.close()
seek()
用来移动文件指针
⽂件对象.seek(偏移量, 起始位置)
起始位置: 0:⽂文件开头,1:当前位置, 2:⽂文件结尾
old_name = input('请输⼊您要备份的⽂件名:') # 2.1 提取⽂件后缀点的下标 index = old_name.rfind('.') #print(index) #后缀中.的下标 #print(old_name[:index]) #源文件名(无后缀) # 2.2 组织新文件名 旧文件名 + [备份] + 后缀 new_name = old_name[:index] + '[备份]' + old_name[index:] # 打印新文件名(带后缀) # print(new_name) # 3.1 打开文件 old_f = open(old_name, 'rb') new_f = open(new_name, 'wb') # 3.2 将源文件数据写入备份文件 while True: con = old_f.read(1024) if len(con) == 0: break new_f.write(con) # 3.3 关闭文件 old_f.close() new_f.close()
import os
os.函数名()
重命名文件:os.rename(⽬标文件名, 新文件名)
删除文件:os.remove(目标⽂件名)
创建文件夹:os.mkdir(文件夹名字)
删除文件夹:os.rmdir(⽂件夹名字)
获取当前目录:os.getcwd()
改变默认目录:os.chdir(目录)
获取目录列表:os.listdir(目录)
应用
需求:批量修改文件名,既可添加指定字符串,又能删除指定字符串。
步骤:
import os # 设置重命名标识:如果为1则添加指定字符, flag取值为2则删除指定字符 flag = 1 # 获取指定目录 dir_name = './' # 获取指定目录的文件列表 file_list = os.listdir(dir_name) #print(file_list) # 遍历文件列表内的文件 for name in file_list: # 添加指定字符 if flag == 1: new_name = 'Python-' + name #删除指定字符 elif flag == 2: num = len('Python-') new_name = name[num:] #打印新文件名,测试程序正确性 print(new_name) #重命名 os.rename(dir_name+name, dir_name+new_name)
用类创建对象
类:对一系列具有相同特征和行为的事物的统称,类是图纸
对象:类创建出来的真实存在的事物
大驼峰命名
# 新式类
class 类名():
代码
.....
# 经典类--不由任意内置类型派生出的类
class 类名:
代码
.....
class Washer():
def wash(self):
print('我会洗衣服')
self指的是调用该函数的对象
对象名 = 类名()
# 创建对象
haier1 = Washer()
# <__main__.Washer object at 0x0000018B7B224240>
print(haier1)
# haier对象调⽤实例方法
haier1.wash()
类外添加对象属性
对象名.属性值 = 值
类外获取对象属性
对象名.属性名
类内获取对象属性
self.属性名
在Python中, __xx__()
的函数叫做魔法方法,指的是具有特殊功能的函数。
初始化对象,自动调用
class Washer():
# 定义初始化功能的函数
def __init__(self):
# 添加实例属性
self.width = 500
self.height = 800
def print_info(self):
# 类里面调用实例属性
print(f'洗⾐衣机的宽度是{self.width}, ⾼高度是{self.height}')
haier1 = Washer()
haier1.print_info()
class Washer():
def __init__(self, width, height):
self.width = width
self.height = height
def print_info(self):
print(f'洗⾐机的宽度是{self.width}')
print(f'洗衣机的⾼度是{self.height}')
haier1 = Washer(10, 20)
haier1.print_info()
haier2 = Washer(30, 40)
haier2.print_info()
当使⽤用print输出对象的时候,默认打印对象的内存地址。如果类定义了 __str__
方法,那么就会打印从在这个方法中 return 的数据。
class Washer():
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return '这是海尔洗衣机的说明书'
haier1 = Washer(10, 20)
# 这是海尔洗⾐机的说明书
print(haier1)
当删除对象时, python解释器也会默认调用 __del__()
方法。
class Washer():
def __init__(self, width, height):
self.width = width
self.height = height
def __del__(self):
print(f'{self}对象已经被删除')
haier1 = Washer(10, 20)
# <__main__.Washer object at 0x0000026118223278> 对象已经被删除
del haier1
Python面向对象的继承指的是多个类之间的所属关系,即子类默认继承父类的所有属性和方法
# 父类A
class A(object):
def __init__(self):
self.num = 1
def info_print(self):
print(self.num)
# 子类B
class B(A):
pass
reuslt = B()
result.info_print() #1
在Python中,所有类默认继承object类, object类是顶级类或基类;其他子类叫做派生类。
# 1. 师⽗父类 class Master(object): def __init__(self): self.kongfu = '[古法煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') # 2. 徒弟类 class Prentice(Master): pass # 3. 创建对象daqiu daqiu = Prentice() # 4. 对象访问实例属性 print(daqiu.kongfu) # 5. 对象调⽤实例方法 daqiu.make_cake()
当⼀个类有多个父类的时候,默认使用第⼀个父类的同名属性和方法。
class Master(object): def __init__(self): self.kongfu = '[古法煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') # 创建学校类 class School(object): def __init__(self): self.kongfu = '[黑马煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') class Prentice(School, Master): pass daqiu = Prentice() print(daqiu.kongfu) daqiu.make_cake()
子类和父类具有同名属性和方法,默认使用子类的同名属性和方法。
class Master(object): def __init__(self): self.kongfu = '[古法煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') class School(object): def __init__(self): self.kongfu = '[黑马煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') # 独创配方 class Prentice(School, Master): def __init__(self): self.kongfu = '[独创煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') daqiu = Prentice() print(daqiu.kongfu) daqiu.make_cake() print(Prentice.__mro__)
class Master(object): def __init__(self): self.kongfu = '[古法煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') class School(object): def __init__(self): self.kongfu = '[黑马煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') # 独创配方 class Prentice(School, Master): def __init__(self): self.kongfu = '[独创煎饼果子配方]' def make_cake(self): # 如果是先调用了父类的属性和方法,父类属性会覆盖⼦类属性,故在调⽤用属性前,先调⽤自⼰子类的初始化 self.__init__() print(f'运⽤{self.kongfu}制作煎饼果子') # 调⽤父类方法,但是为保证调用到的也是父类的属性,必须在调用方法前调用父类的初始化 def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) daqiu = Pretice() daqiu.make_cake() daqiu.make_master_cake() daqiu.make_school_cake() daqiu.make_cake()
class Master(object): def __init__(self): self.kongfu = '[古法煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') class School(object): def __init__(self): self.kongfu = '[黑马煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') # 独创配方 class Prentice(School, Master): def __init__(self): self.kongfu = '[独创煎饼果子配方]' def make_cake(self): self.__init__() print(f'运⽤{self.kongfu}制作煎饼果子') def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # 徒孙类 class Tusun(Pretice): pass xiaoqiu = Tusun() xiaoqiu.make_cake() xiaoqiu.make_school_cake() xiaoqiu.make_master_cake()
class Master(object): def __init__(self): self.kongfu = '[古法煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') class School(Master): def __init__(self): self.kongfu = '[黑马煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') #方法2.1 #super(School,self).__init__() #super(School,self).make_cake() #方法2.2 super().__init__() super().make_cake() class Prentice(School): def __init__(self): self.kongfu = '[独创煎饼果⼦技术]' def make_cake(self): self.__init__() print(f'运⽤{self.kongfu}制作煎饼果子') # ⼦类调⽤用父类的同名方法和属性:把父类的同名属性和方法再次封装 def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # ⼀次性调⽤父类的同名属性和方法 def make_old_cake(self): # 方法一: 代码冗余;父类类名如果变化,这里代码需要频繁修改 # Master.__init__(self) # Master.make_cake(self) # School.__init__(self) # School.make_cake(self) # 方法二: super() # 方法2.1 super(当前类名,self).函数() # super(Pretice,self).__init__() # super(Pretice,self).make_cake() # 方法2.2 super().函数() super().__init__() super().make_cake() daqiu = Prentice() daqiu.make_old_cake()
calss 类名():
# 私有属性
__属性名 = 值
# 私有方法
def __函数名(self):
代码
在Python中,可以为实例属性和方法设置私有权限,即设置某个实例属性或实例方法不继承给子类。
私有属性和私有变量只能在类里面访问和修改
class Master(object): def __init__(self): self.kongfu = '[古法煎饼果⼦配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') class School(object): def __init__(self): self.kongfu = '[⿊马煎饼果子配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果子') class Pretice(School,Master): def __init__(self): self.kongfu = '[独创煎饼果子配方]' #定义私有属性 self.__money = 2000000 #定义私有方法 def _info_print(self): print(self.kongfu) print(self.__money) def make_cake(self): self.__init__() print(f'运用{self.kongfu}制作煎饼果子') def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # 徒孙类 class Tusun(Prentice): pass daqiu = Prentice() #对象不能访问私有属性和私有方法 #print(daqiu.__money) #daqiu.__info_print() xiaoqiu = Tusun() # 子类无法继承父类的私有属性和私有方法 # print(xiaoqiu.__money) # 无法访问实例属性__money # xiaoqiu.__info_print()
在Python中,⼀般定义函数名 get_xx
用来获取私有属性,定义 set_xx
用来修改私有属性值。
class Master(object): def __init__(self): self.kongfu = '[古法煎饼果⼦配方]' def make_cake(self): print(f'运⽤{self.kongfu}制作煎饼果⼦') class School(object): def __init__(self): self.kongfu = '[⿊马煎饼果⼦配方]' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子') class Prentice(School, Master): def __init__(self): self.kongfu = '[独创煎饼果⼦配方]' self.__money = 2000000 #获取私有属性 def get_money(self): return self.__money # 修改私有属性 def set_money(self): self.__money = 500 def __info_print(self): print(self.kongfu) print(self.__money) def make_cake(self): self.__init__() print(f'运⽤{self.kongfu}制作煎饼果子') def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) #徒孙类 class Tusun(Prentice): pass daqiu = Prentice() xiaoqiu = Tusun() #调用get_money函数获取私有属性money的值 print(xiaoqiu.get_money()) # 调用set_money函数修改私有属性money的值 xiaoqiu.set_money() print(xiaoqiu.get_money())
封装:
继承:
多态
class Dog(object): def work(self): #父类提供统一的方法,哪怕是空方法\ print('指哪打哪') class ArmyDog(Dog): # 继承Dog类 def work(self): # 子类重写父类同名方法 print('追击敌人') class DrugDog(Dog): def work(self): print('追查毒品') class Person(object): def work_with_dog(self,dog): #传入不同的对象,执行不同的代码,即不同的work函数 dog.work() ad = ArmyDog() dd = DrugDog() daqiu = Person() daqiu.work_with_dog(ad) daqiu.work_with_dog(dd)
类属性就是类对象所拥有的属性,被该类的所有实例对象所共有
类属性可以使用类对象或实例对象访问
类属性的优点
class Dog(object):
tooth = 10
wangcai = Dog()
xiaohei = Dog()
print(Dog.tooth)
print(wangcai.tooth)
print(xiaohei.tooth)
class Dog(object): tooth = 10 wangcai = Dog() xiaohei = Dog() # 修改类属性 Dog.tooth = 12 print(Dog.tooth) #12 print(wangcai.tooth) #12 print(xiaohei.tooth) #12 #不能通过对象修改属性,如果这样操作,实则是创建了一个实例属性 wangcai.tooth = 20 print(Dog.tooth) #12 print(wangcai.tooth) #20 print(xiaohei.tooth) #12
class Dog(object):
def __init__(self):
self.age = 5
def info_print(self):
print(self.age)
wangcai = Dog()
print(wangcai.age) #5
# print(Dog.age) #报错,实例属性不能通过类访问
wangcai.info_print() #5
@classmethod
来标识其为类方法,对于类方法, 第一个参数必须是类对象,一般以cls
作为第⼀个参数。class Dog(object):
__tooth = 10
@classmethod
def get_tooth(cls):
return cls.tooth
wangcai =Dog()
result = wangcai.get_tooth()
print(result) #10
@staticmethod
进行修饰,静态方法既不需要传递类对象也不需要传递实例对象(形参没有self/cls)class Dog(object):
@staticmethod
def info_print():
print('这是⼀个狗类,用于创建狗实例....')
wangcai = Dog()
# 静态方法既可以使用对象访问又可以使用类访问
wangcai.info_print()
Dog.info_print()
try:
可能发生错误的代码
except:
如果出现异常执行的代码
try:
f = open('test.txt','r')
except:
f = open('test.txt','w')
try:
可能发生错误的代码
except 异常类型:
如果捕获到该异常类型执行的代码
try:
print(num)
except NameError:
print('有错误')
当捕获多个异常时,可以把要捕获的异常类型的名字,放到except 后,并使用元组的方式进行书写
try:
print(1/0)
except (NameError,ZeroDivisionError):
print('有错误')
try:
print(num)
except (NameError,ZeroDivisionError) as result:
print(result)
Exception是所有程序异常类的父类
try:
print(num)
except Exception as result:
print(result)
else表示的是如果没有异常执行的代码
try:
print(1)
except Exception as result:
print(result)
else:
print('我是else,是没有异常的时候执行的代码')
finally表示的是无论是否异常都要执行的代码
try:
f = open('test.txt','r')
except Exception as result:
f = open('test.txt','w')
else:
print('没异常')
finally:
f.close()
需求:
import time try: f = open('test.txt') try: while True: content = f.readline() if len(content) == 0 break time.sleep(2) print(content) except: # 如果在读取文件的过程中,产⽣了异常,那么就会捕获到 # 比如 按下了了ctrl+c print('意外终⽌了读取数据') finally: f.close() print('关闭文件') except: print("没有这个文件")
在Python中,抛出自定义异常的语法为 raise 异常类对象
。
需求:密码长度不足,则报异常(用户输入密码,如果输入的长度不足3位,则报错,即抛出自定义异常,并捕获该异常)。
# 自定义异常,继承Exception class ShortInputError(Exception): def __init__(self,length,min_len): self.length = length self.min_len = min_len #设置抛出异常的描述信息 def __str__(self): return f'你输⼊的长度是{self.length}, 不能少于{self.min_len}个字符' def main(): try: con = input('请输入密码:') if len(con) < 3: raise ShortInputError(len(con),3) except Exception as result: print(result) else: print('密码已经输入完成') main()
# 1. 导入模块
import 模块名
import 模块名1,模块2...
# 2. 调用功能
模块名.功能名()
import math
print(math.sqrt(9)) #3.0
from 模块名 import 功能1, 功能2, 功能3..
from math import sqrt
print(sqrt(9))
from 模块名 import *
from math improt *
print(sqrt(9))
# 模块定义别名
import 模块名 as 别名
# 功能定义别名
from 模块名 import 功能 as 别名
# 模块别名
import time as tt
tt.sleep(2)
print('hello')
#功能别名
from time import sleep as sl
sl(2)
print('hello')
在Python中,每个Python文件都可以作为⼀个模块,模块的名字就是文件的名字。 也就是说自定义模块名必须要符合标识符命名规则。
# my_module1.py
def testA(a,b):
print (a + b)
# 只有当前文件中调用该函数,其他导入的文件内不符合该条件,则不执行testA函数调用
if __name__ == '__main++':
testA(1,1)
import my_module1
my_module1.testA(1,1)
如果使用 from .. import ..
或 from .. import *
导入多个模块的时候,且模块内有同名功能。当调用这个同名功能的时候,调用到的是后面导入的模块的功能。
# 模块1代码
def my_test(a,b):
print(a + b)
# 模块2代码
def my_test(a,b)
print(a - b)
#导入模块和调用功能代码
from my_module1 import my_test
from my_module1 import my_test
# my_test函数是模块2中的函数
my_test(1,1)
当导⼊一个模块, Python解析器对模块位置的搜索顺序是:
模块搜索路径存储在system模块的sys.path变量中。变量里包含当前目录, PYTHONPATH和由安装过程决定的默认目录。
如果⼀个模块文件中有 __all__
变量,当使用 from xxx import *
导入时,只能导入这个列表中的元素。
__all__ = ['testA']
def testA():
print('testA')
def testB():
print('testB')
from my_module1 import *
testA()
testB() # 异常 未定义
包将有联系的模块组织在⼀起,即放到同⼀个文件夹下,并且在这个文件夹创建一个名字为 init.py 文件,那么这个⽂件夹就称之为包。
[New] — [Python Package] — 输⼊入包名 — [OK] — 新建功能模块(有联系的模块)。(PyCharm)
注意:新建包后,包内部会自动创建 __init__.py
文件,这个文件控制着包的导入行为。
# my_module1
print(1)
def info_print1():
print('my_module1')
# my_module2
print(2)
def info_print2():
`print('my_module2')
import 包名.模块名
包名.模块名.目标
import my_package.my_module1
my_package.my_module1.info_print1()
必须在 __init__.py
文件中添加 __all__ = []
,控制允许导入的模块列表。
from 包名 import *
模块名.目标
from my_package import *
my_module1.info_print1()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。