Python基础

Python基础

lesson_1——Python介绍

print('-----lesson_1 快速入门-----')

知识汇总:

1-Python介绍

2-语言的执行方式:

1-编译执行:c / c++ / java(javac编译器)

1- 编译+链接

2-一旦有语法错误,不能运行---笔译

3-exe---执行文件

2-解释型:

1-口译---边执行边翻译

3-python官网:https://www.python.org/

4-从print开始:

1-hello.py去运行 cmd -----python hello.py

2-在解释器里面运行

1-进入解释器 >>>

2-输入 print('hello')

3-pycharm运行

4-<u>严格区分大小写</u>

5-第一条语句前面不能有空格 ,但可以空行

6- print在python3一定要有小括号()

lesson_2——对象+变量

print('---lesson_2对象+变量---')

知识汇总:

1-Python 语言里 一切数据都是对象

2-整数:

1-python 2 :int ---- long(长整数)

2-python 3 :只有int 没有long

3-怎么查看类型---type(100)--有返回值--该类型---<class 'int'>

3-浮点数--小数:type(3.0)---<class 'float'>---没有double

4-数字的运算:

1-加法 +

2-减法 -

3-乘法 *

4-除法 /

1-在python3 9/4 == 2.25 肯定带小数点 等价python2- 9//4 == 2

2-在python2 9/4 == 2 等价python3------ 9.0/4 == 2.25

5-取余 %

6-求次方----2**4

5-字符串:

1-定义:<class 'str'>

1- ' a' " a" ''' ''' ——单引号、双引号、三引号

6-字面量--直接量-- 1 3.14 'a'

7-变量:

1-优点:

1-代码比较简洁

2-修改方便

2-字符串之间的连接符: +

3-变量:一个名字---一个可以改变的

1-组成:字母+数字+下划线

2-一般以字母(大写,小写均可)开头---本身没有语法错误

3-数字不能开头!!!

4-区分大小写

5-英文单词--建议

6-不能与关键字相同(关键字是Python语言里面的特殊字符串)

import keyword

print(keyword.kwlist)

7-不要与内置函数相同---print

4-没有任何变量引用的对象,会被Python解释器清除

5-查看对象的地址--id() print('a的值:',a,'a的地址', id(a))

8-退出python解释器:

1-ctrl+ z--*

2-exit()

3-quit()

9-常见的几种变量的赋值

1- a= 1

2- a += 1 ------- a = a + 1

3- a *= 2 ------- a = a * 2

4- a++ ++a a-- --a python语法里面没有这些

10-ctrl + / --- 注释/取消注释

11- print(round(1/3,6))--精确小数位数

print(type(100.0)) #type()----查看类型---<class float'>

print(round(2/3,3)) #指定精度--四舍五入

print(2**4)

print('hello '+' python')

print('hello'+3) #TypeError: must be str, not int

print(3+'hello') #TypeError: unsupported operand type(s) for +: 'int' and 'str'

welcome = '欢迎来到自动化班学习--python'

print('小A' + welcome)

print('小B' + welcome)

print('小C' + welcome)

print('小D' + welcome)

3a = 100 #数字不能开头

_data = 100 #普遍变量----不建议下划线

name = 'tom' #首选字母开头

getName = ''

get_name = ''#

a = 1

b1 = ''

print('');print();print();print() #不建议

import keyword

print(keyword.kwlist)

name = 'tom'

name = 'jack'

print(name)

lesson_3——字符串

print('---lesson3_字符串---')

知识点汇总:

1-什么是字符串

2-字符串的定义:内容元素不可改变

1- 单引号 - '' -----type(name) <class 'str'>

2- 双引号 - "" -----"tom"

注意:不能混着 SyntaxError: EOL while scanning string literal

3- 三引号 ''' ''' """ """

使用区别:

1- 如果字符串本身有' 那么就用双引号 "

2- 如果字符串本身有" 那么就用单引号 '

3- 可以使用转义 \

4- 三引号:

1-字符串定义

2-注释

3-多行 '3.14'

3-拼接:

1-多个字符串进行连接:连接符 +

2-多个相同字符串连接:字符串*n

4-sequence(序列)

1-特性:

1-编号-序号-下标--------唯一的

2-元素

3-空字符串 str1 = ''

2-字符串-序列类型

1-下标 :

1-正下标---从左边 0 开始 到 长度-1

name = 'tom'---name[3]--- IndexError: string index out of range

2-负下标---从右边 -1开始

3-len()---计算序列的长度---有返回值--就是计算的对象的长度

4-切片: str1[start:end:step]

特性:1-下标 ; 2-左含右不含

1-取中间段

1-string1[start:end], 从start 开始,到end结束,但不包括end

2-str1[获取内容的首字符下标:该下标+长度] ---*

2-取尾部:

1-string1[start:], 从start 开始,到字符串结束

3-取头部:

string1[:end], 从第一个字符 开始,到end位置结束,但不包括end

4-什么时候用正下标或者负下标?

1-看被切对象

2-如果左右都变化--切片不好操作---后续讲解----split

5-被切对象,切完之后会不会改变?---不会改变,只是切出来的对象,作为一个新对象!

1- 切中间某一段:str1[3:3+4]

2- 切前一段:str1[:7] --留前,写尾

3- 切后一段:str1[7:] --留尾,写前

str1[第一个切点下标:第2个切点下标:步长] #步长默认是1

注释/取消注释: ctrl + /

info = 'name is ' tom'

print(info)

print(len(info)) #求长度

print('hello\n'*3)

print('hello','tom',sep='')

print(round(100/3,6)) #33.333333

info = 'name is tom' #字符串就是序列类型

print(len(info))

print(info[len(info)-1]) #获取最后一个元素

负下标---从右边开始算--- -1 开始

print(info[0-len(info)]) #最前面一个元素

print(info[0],info[-1]) #推荐

1- 获取中间一段 info[第1刀下标:第2刀下标]---不会对原有字符串产生影响

print(info[5:5+2]) #左含右不含

print(info)

2- 获取前半段--- 写后面一个下标

print(info[:4])

3- 获取后半段-- 写前面的一个下标

print(info[4:])

str1 = '11:12:11> 001 enter chatroom, level 2'

print(str1[10:10+3])

print(info[::-1]) #字符串的倒序--【start:end:step】

print(info[0:4:2]) #nm

print(info.index('a')) #获取下标

lesson_4­­——列表+元组

print('---lesson4_列表+元组---')

知识点汇总:

1-列表---List

1-特性:

1-列表也是一种Sequence 类型

2-下标

3-能切片

4-可以存储任何类型的数据,每个元素是任意类型

5-内容可以改变:增删改查

1-改变元素值 alist[0] = 9

2-个数 alist.append(5)---增加后面---追加

3-增加元素--alist.append--尾部 -- insert()--任意位置

4-删除元素 ----del alist[0]、del alist[0:2]、alist.pop(下标)、alist.remove(alist[1])

2-列表的定义:

1- []---英文的中括号

2-type([])---- <class 'list'>

3- 例子: alist = [1,3.14,'abc',[100,200]]、一个元素 alist = [1]

3-列表的使用

1-获取列表元素 -- 列表名[下标]

2-每一个元素用 , 隔开

3-切片-切出来的对象跟被切对象类型一样

2-元组:

1-元组跟我们大家熟悉的数组是一样的吗???

1-数组:同一类型

2-元组:任意类型

特性:

1-元组也是一种Sequence 类型

2-下标

3-能切片

4-可以存储任何类型的数据,每个元素是任意类型

5-内容不可以改变!!!

2-元组的定义:

1- 空元组 ()---type(())----<class 'tuple'>

2-一个元素的元组 tu1 = (1,)

3-元组的使用:

1- 下标获取值

2- 切片

3- 不能改变本身的内容,否则

TypeError: 'tuple' object does not support item assignment

总结:

1-字符串 和 元组不能改变值和数量,否则:

TypeError: 'str' object does not support item assignment

2-存储角度:

1- 元组---任意类型

2- 列表---任意类型

3-元组和列表可以通过函数转换:

1- 元组转列表 alist = lsit(元组)

2- 列表转元组 tu1 = tuple(列表)

4-列表和元组定义一个元素的时候区别

1- 列表 [1]

2- 元组 (1,)

5-使用场景:

1-列表---存储的对象内容是可以改变的 如 排序

2-元组---存储的对象不想让其他人去改变----- 配置参数

需求:

1- 保存全班学生的信息 - list tuple 都可以

2- 可以修改每一个学生信息 list

3- 可以增加/删除-学生的信息 list

stu_info = [

[名字,年龄,性别],

[名字,年龄,性别],

[名字,年龄,性别]

]

alist = [10,3.14,'hello',[1,3,5]] #列表的定义

print(type(alist)) #<class 'list'>

print(len(alist))

print(alist[-1][-1]) #1- 查找元素

print(5 in alist[-1])

print(alist[0:0+1]) #列表切片出来是列表

print(alist[-1][0:0+2]) #[1, 3]

alist[0] = 20 #2- 修改值

alist.append(200) #3- 增加元素的操作---尾部增加

alist.insert(0,200) #4- 增加元素--任意位置

需求: 合并一个列表 [1,2,3,4,5]

alist = [1,2,3]

alist.append([4,5])

alist.extend(['hello',5]) #合并列表,永久

print(alist+[4,5]) #临时

5- 删除

del alist[0],alist[2] #IndexError: list assignment index out of range

del alist[0],alist[1] #不建议这样写

del alist[0:2] #[3]

res = alist.pop(0) #pop()返回一个被删除的值

print(res)

alist.remove(alist[1]) #直接删除值---效率比前面2种低

print(alist)

tu1 = (10,3.14,'hello',[1,3,5],(100,200)) #一个元素的时候,一定加一个逗号

print(type(tu1)) #<class 'tuple'>

print(tu1[0:1])

1-元组不支持修改元素的值--TypeError: 'tuple' object does not support item assignment

tu1[0] = 20

2-元组不能改变元素的个数

alist = [1,2,3,4]

print(tuple(alist)) #列表转元组--(1, 2, 3, 4)

tu2 = (10,20,30,40)

print(list(tu2)) #元组转换成列表 [10, 20, 30, 40]

b = [1,2,3]

b.insert(1,[2]) #指定下标位置插入元素

print(b)

print(alist .append(200)) #尾端插入元素

print(alist)

python垃圾回收机制

https://www.cnblogs.com/pinganzi/p/6646742.html

lesson_5——布尔表达式

print('---lesson5_布尔表达式---')

知识点汇总:

1-布尔类型:

特性:只有2种情况-- 真 / 假

1- True False

2- type(True)----- <class 'bool'>

2-布尔表达式:

1- 它的结果是bool

2- 关系运算 3>1 关系的等价 == 一个等号是赋值 不等价 !=

3- 字符串的比较:

1- 是比较长度吗?---- 不成立

2- 比较的是字符串对应的ASCII值 A--65 a--97

4- 逻辑运算

3- in not in 布尔结果

1- in 在里面

2- not in 不在里面

3- str tuple list

4- (1,3) in (1,3,5)---False

4-条件组合

1-且:条件1 and 条件2

1- 其中一个为False---整个表达式= False---一假全假,全真为真

2- 如果条件1 == True ,条件2,一定会执行(判断)

3- 如果条件1 == False ,条件2,一定不会执行(判断)

2-或:条件1 or 条件2

1- 其中一个为True---整个表达式=True--0- 一真全真,全假为假

2- 如果条件1 == True ,条件2,一定不会执行(判断)

3- 如果条件1 == False ,条件2,一定会执行(判断)

3- 不-- not

1- 取反 True--- False

4- 优先级

1- 没有任何括号的情况下 not > and > or

2- 建议多打括号 (3(2(1)))---从里到外

3- 复杂的逻辑关系---建议注释

isSelect = True

print(type(isSelect)) #<class 'bool'>

a = 257

b = 257

print(a == b) # 值相等 地址一样吗? -5 256 ---值相等 & 地址--也相等

print(a is b) # 值 + 地址都一样

print(id(a),id(b))

print('abcd' > 'ab')

1- 字符串里: 1- 前面是后面的一个元素 2-也可以是连续一段

info = 'abcde'

print('ace' not in info)

2- 列表---1- 前面是后面的一个元素

alist = [1,3,5,7,[1,3]]

print([1,3] in alist)

def func():

print('我执行了!')

return True

func() #调用函数

if 3 == 1 or func(): # 全真为真----真

print('条件满足!---爬山')

print((not 3==1) and (4>2)) # 优先级: not and or

nameList = ['tom','jack','tim']

if 'jack' in nameList:

print('找到了')

if 'jack' not in nameList:

print('不调研!')

print(3==3 or 3<1 and 4>1)

print(3==3 or False)

lesson_6——条件判断

print('---lesson6_条件判断---')

知识点汇总

1-流程控制:

1-顺序结构--一步步执行

2-选择结构--在某一步选择性执行

3-循环结构--在一定条件下,一直执行某段代码(事情)

2-条件判断

1- if --如果

1- if 条件==True: 执行if里面的语句

2- if xxx: .... else: 如果--否则

1- 只有2种情况,肯定会执行其中一个

2- 对立面的情况下使用

3- 多种分支 if.... elif..... else

1- 最后的else 选配

2- 只要满足其中一个分支,就退出if的语句结构

4-if的嵌套

1- 要执行内部的if 一定要外部的if 满足才可以

2- 相当于and

5-switch语句---没有这个语法

6-多条件可以分行写

7-注释/取消注释 ctrl + /

8-扩展;

1- if如果后面跟是 非0的数值、非空字符串 、非空元组、非空列表,该if 的条件结果就为True

9-input()--函数--接收字符--返回的是字符串!

需求:判断用户输入的手机号是否有效,输出对应的运营商!

思路:

1- if(tel == 11):位数

if(是否纯数字):1234567989a

if(号段==187) or (==139) or():前3位 in list:

移动

elif(号段==132) or (==176) or():

联通

elif(号段==199) or (==198) or():

电信

else:

提示:无此号段

else:

提示:有非法字符

else:

提示:位数有误!

tel = input('输入手机号:') #控制台输入--返回是一个字符串

print(tel)

1- 单 if 语句

1- 如果是 : 后面一定要有语句---pass----空语句

2- 场景: 当只需要对条件满足的时候处理,不满足不做任何处理

2- if -- else: 如果--否则

1- 一定会执行其中一个

场景: 需要对条件不满足的情况也进行处理

3- if 多分支-- > 2种以上情况的选择

4- else --根据自己需求来

1- if 单语句------场景:只需要对满足条件的处理------不满足的不需要处理

score = 80

if score >= 60:

print('及格了')

# pass#空语句---顶个位置

print('run--over!')

2- if else :场景: 满足需要处理,不满足也需要处理

score = 80

if score >= 60:

print('及格了')

# pass#空语句---顶个位置

else:

print('再接再厉')

3- if else :场景: 满足需要处理,不满足也需要处理

tab---往后缩进 shift+tab----往前缩进

score = 85

if score >= 90:

print('A等级')

elif score >= 80:

print('B等级')

elif score >= 70:

print('C等级')

elif score >= 60:

print('D等级')

else:#选配

print('再接再厉')

print('run--over!')

----------不建议如下写法

score = 85

if score >= 90:

print('A等级')

if score >= 80 and score < 90:

print('B等级')

if score >= 70 and score < 80:

print('C等级')

if score >= 60 and score < 70:

print('D等级')

if score < 60:#选配

print('再接再厉')

print('run--over!')

扩展---if 嵌套结构---一个场景需要分阶段(层次)做出不同处理

score = 85

if score >= 60:

if score >= 90:

print('A等级')

else:

if score >= 80:

print('B等级!')

else:

pass

else:

print('不及格!')

print('run--over!')

score = input('请输入分数:') #1- 只要敲回车才结束! 2- 接收是字符串

print(type(score)) #字符串

print(int(score)+20)

sex = input('请输入性别:')

if int(score) >= 90 \ #尾部加’\’换行写

and sex == 'M':

print('A---男同学')

if 如果这个条件要是 True

: True 、非零数值、非空字符串、非空元组、非空列表

if ' ':

print('条件满足!')

lesson_7——函数

print('----lessson 7-函数----')

知识点汇总:

1-函数的概念:

1-就是一段代码

2-一段操作流程

优点:

1- 代码量少-简洁

2- 维护起来方便---在函数的定义进行修改

2-函数的定义:

1-def 函数名():

函数内容

2- 函数的定义是不会执行函数内容的代码的!

3-案例:

def func():

print('step1')

print('step2')

4- type(func) ----<class 'function'>

3-函数的调用

1- func()

2- 调用的时候才去执行

3- 函数的定义一定要在函数的调用前面

4- 参数

1- 形参:

1-在函数定义的参数 def func(a,b): a , b 都是形参

2-在pycharm 形参如果没有被使用是灰色的,使用了的是黑色

3-def func(a,b): 一般只要参数名的参数---必填形参,没有限制类型

2- 实参

1- 在函数调用的时候实际传入的参数 func(1,2) 1, 2都是实参

3-函数的调用的时候不能使用如下写法:func(a=1,2)

5- 返回值

1- 函数调用完成后,会有返回值

2- 在函数里面有 return 值

3- 返回值类型:

1- None----没有return

2- 任意类型

3- 函数的返回值类型--取决于return 后面的类型

4- 在return 后面的语句不会执行--函数一旦执行到return该函数已经调用完成

6- 全局变量+局部变量

1- 全局变量:在一个.py文件里面,一旦定义好一个变量,后面的所有代码都可以使用

2- 局部变量:在函数内部的

7- 类型转换-内置函数

1- int()---转换成int

1- 被转换的内容一定是纯数值

2- str()--转换成字符串

3- float()--转换成浮点数

注意事项:

a = 3.14---float类型

print(int(a))----舍弃小数部分取整---3

a ='3.14'---str类型

print(int(a))----报错,不能是小数的数值内容

8- input()---返回值是str

函数:在次序上,先定义再调用-----函数调用前,一定是定义了

def func(): #函数定义---不会执行函数里面的代码

print('step1')

print('step2')

print('step3')

func()#函数的调用!----执行函数的代码

print('run--over!')

def func(a,b):

print(a,b)

func((),[]) #函数调用

def get_sum(a,b):

print(a+b)

get_sum('hello','world')

def func(a,b):

# print(a+b)

return a+b

res = func(1,2)+10

print(res)

print(func(1,2))

def get_res(a,b):

if a > b:

return 1

elif a < b:

return -1

else:

return 0

res = get_res(1,2)

if res != 0:

print('两数不等于!')

def func():

return (1,2,3)

print(func())

a = [100,200]

b = str(a) #把xxx转换成str

print(type(b))

a = '3.14'

b = int(a) #把里面的内容转成int: 要求:字符串里面的内容:一定是整型的数值---不能是小数

print(type(b))

a = 3.999

b = int(a) #把里面的内容转成int: 只取整数部分

print(type(b))

print(b)

lesson_8——对象方法

print('----lesson8_对象方法----')

知识点汇总:

1- 对象的方法:

这个对象类型在标准库里面就有的方法

2- 对象的方法调用

对象.方法

3- 字符串---str

1-count() 计算字符串中包含的多少个指定的子字符串

str1 = 'abcaaa' ----str1.count('a') - 结果 4

2-endswith() 检查字符串是否以指定的字符串结尾 --返回值 bool

3-startswith() 检查字符串是否以指定的字符串开头 --返回值 bool

4-find() 返回指定的子字符串在字符串中出现的位置

1- 只返回查找第一个出现的位置

2- str1.find('a',3) 指定开始查找下标位置

3- 如果要查找的内容,不在该对象里面,那么该方法返回 -1

5-isalpha() 检查字符串中是否都是字母 ---返回值 bool

6-isdigit() 检查字符串中是否都是数字 ---返回值 bool

7-str.join() 将 sequence类型的参数的元素字符串合并(连接)到一个字符串,string 作为分隔符

alist = ['i','like', 'football']

print('*'.join(alist))

8-split(‘str’) 将字符串分割为几个子字符串。参数为分隔符

str1 = 'abc,def,hijk'

print(str1.split(','))

1- 返回类型是list--列表

2- 那个切点还有吗? 切点会被切掉

9-lower() 将字符串里面如果有大写字母的全部转为小写字母

10-upper() 将字符串里面如果有小写字母的全部转为大写字母

11-replace(‘old’,’new’,n) 替换字符串里面指定的n个子字符串

str1 = 'abcaa'

print(str1.replace('a','x',2))

注意点: n省略则替换全部

12-strip() 将字符串前置空格和后置空格删除 不能去中间空格

13-lstrip将字符串前置空格删除

14-rstrip将字符串后置空格删除

4- 列表

1-append(),给列表添加一个元素 在列表尾部

2-insert(),给列表指定位置插入一个元素

alist.insert(需要插入的位置的下标,插入的值)

3-列表删除元素

1- del alist[下标]

2- alist.pop(下标) 该方法有返回值,是被删元素

3- alist.remove(元素) ----效率最低,无返回值

4- alist.clear()--清空列表

5- reverse(),将列表里面元素倒序排列

str1 = 'abcdefabbbb'

# print(str1.count('x'))

print(str1.find('a',2)) #返回是元素a的下标---如果元素不存在----返回-1

if str1.find('x') != -1: #判断是否存在

print('该元素存在')

print('\n'.join(['i','like','play','football']))

1-里面填入--切点 ;2- 切点会消失 ; 3- 返回是 list;

4- 如果切点不存在--不操作--变成列表

info = ' name is tom '

resList = info.split('x')

print(resList)

print(resList[1])

print(info.replace('tom','jack')) #默认全部替换

alist = [1,2,3]

alist.insert(5,100) #插入下标大于长度,则在末尾插入

print(alist)

print(alist[::-1]) #翻转,相当于 alist.reverse(),但alist.reverse()改变了alist

lesson_9——字符串格式化输入输出

print('---lesson9_字符串格式化输出+输入---')

知识点汇总;

1-字符串格式化输出方法一: %

1-print('名字是 %s,年龄是%s' % (name ,age))

2- %s ---字符串-----相当于执行了str()

3- (name ,age) 只能是元组,不能是列表

4-多个数据的打印,一定是元组

5- %d--十进制

6- %f--6位小数

7- %x—16进制

8-指定长度打印----数值和字符串一样的

1- %5d 右对齐,不足左边补空格

2- %-5d 左对齐,不足右边补空格

3- 补0 %05d

9- 十六进制:%#x # 加一个 0x

10-小数--float

1- 默认是6位

2- 指定保留小数位数- %.3f-----进行了四舍五入

3- %6.3f ---- 6代表总长度(包括 . )

4- %08.3f ---- 补0

2-字符串格式化输出方法二: format()---固定的 {}

1- 顺序填坑:

1- 可以有元素多,不能有元素少!

print('****名字是 {},年龄是 {}'.format(name ,age))

2- 下标填坑:

1- 不能下标越界 IndexError: tuple index out of range

print('名字是 {1},年龄是 {0}'.format(name ,age))

3- 变量方法

1- print('名字是 {name},年龄是 {age}'.format(name='tom' ,age = 18))

4-指定长度输出:

1- {:长度}

1- 数值型:右对齐,左补齐

2- 字符串:左对齐,右补齐

2- > 右对齐

3- < 左对齐

4- ^ 中间对齐 --- print('我叫:{:0^10},年龄是:{:0<5}'.format(name,age))

5- 数值补0 ,一般是右对齐 ,左补0 ,不改变值

6- 字符串本身带花括号 {{}}

3- python 3.6 以后 f''

print(f'名字是{name},年龄是{age}')

4- 转义符 \

print('name is \n tom')

5- input()---控制台的终端输入

1- 有返回值---str

2- 如果对得到的值进行算术---int()、float()

3- 用户的输入是以一个回车符结束---不敲回车就死等

name = 'tom'

age = 20

print('名字是: '+name+'年龄是: '+str(age))

info = '名字是: '+name+'年龄是: '+str(age) #字符串格式化

print(info)

print('名字是:%s , 年龄是:%6s ' % (name,age)) #%s---字符串#

print('%06s' % name)

print('%#x' % 108) # 108/16----商6 余数 12--c----0x6c

print('%#X' % 108)

print('%1.3f' % 3.1415926) # %f 保留3位小数,格式输出默认是6位---四舍五入

------------------format格式化----------------------

1-补齐符号,对齐方式

info = '名字是:{:^6},年龄是:{:^6}'.format(name,age)

print(info)

2- 下标填坑

info = '名字是:{0},年龄是:{4}'.format(name,100,1,3,4,5)

print(info)

3- 变量填坑

info = '名字是:{name},年龄是:{age},{{}}'.format(name = 'tom',age = 18)

print(info)

info = f'名字是:{name:>6},年龄是:{age:>6}' #python3.6之后有的

print(info)

lesson_10——循环

print('---lesson10_循环---')

知识点汇总;

1-循环概念

1-在一定条件下,重复做某件事件(代码)

2- while循环

1- while 条件表达式:

循环体

2- 当 条件表达式 == True ,才执行循环内容

3- 有循环递增变量

sumData = 0

cnt = 1

while cnt < 101:

sumData += cnt

cnt += 1

print(sumData)

4- 死循环 一定是bug?---不一定

1- 有优点

2- 一般功能的死循环都是结合一定条件下的 break

while True:

psw = input('请输入密码:')

print('你再循环!,按 q 退出!')

if psw == 'q':

break

3- for 循环--遍历的手法

1- for name in alist:

print(name)

2- 打印 1---10

range(1,11)---左含右不含

for one in range(1,11):

print(one)

4- break 跳出本层循环!

alist = ['Mike', 'Jack', 'Mary', 'Pat','Will','Lisa']

for one in range(0,2): # 2次 0 1

for name in alist:

print(name)

if name == 'Jack':

break

5- continue --结束本次循环

1- 当continue的条件满足的时候,它后面的语句要执行吗? -- 不要!

6- 注释

1- 作用:

1- 备注

2- 不执行

2- 方法:

1- # 单行

1- 在该行代码前面,不执行该行代码

2- 在该行代码后面--备注

2- 多行

1- 注释/取消注释 ctrl+ /

2- 三引号

3- 函数内容注释

def func():

'this is func doc'

print('函数!')

print(func.doc)

7-循环:

1- while:循环次数不定,循环靠条件结束

2- for:遍历操作--指定次数循环

1+2+3+4+....100

def get_sum(start,end):

cnt = start

sumData = 0 #结果

while cnt <= end: #重复执行里面的代码

sumData += cnt

cnt += 1

return sumData

print(get_sum(1,10))

while True: #不考虑循环次数--循环结束靠条件触发

password = input('请输入密码:')

if password == '123':

print('密码正确!')

break #结束循环!

nameList.append('lili')

while

def name_print(inList):

indx = 0 #下标

while indx < len(inList):

print(inList[indx])

indx += 1

name_print(nameList)

for name in (1,3,5,7): #遍历操作

print(name)

for one in range(0,10): #取次数--范围值 左含右不含

print('hello')

for one in range(0,10,2): #取次数--范围值 左含右不含 0 2 4 6 8

print(one)

nameList = ['Mike', 'Jack', 'Mary']

for name in nameList:

if name == 'Jack':

# break #结束本层循环

continue #结束本次循环,继续下次循环

print(name)

for one in range(0,2): #循环2次 0 1_-外循环

for name in nameList: #内层循环

if name == 'Jack':

break

print(name)

---------------------下面是我的xxx代码------------

---------------------get_sum函数------------

def get_sum(start,end):

'''

:param start:

:param end:

:return:

'''

cnt = start

sumData = 0 #结果

while cnt <= end: #重复执行里面的代码

sumData += cnt

cnt += 1

return sumData,1,2,3,4

------------------------over--------------------

print(get_sum.doc)#函数的说明

print(print.doc)

课堂作业: 9*9------乘法表

lesson_11——文件读写

print('---lesson11_文件读写---')

知识点汇总

1-文件

1- Python2 File -- Python3 TextIOWrapper

2-文件的打开:

1- fo = open(file,mode)-----函数---有返回值--文件对象

2- 一定要有file文件路径(路径、文件名、文件格式) 否则

TypeError: Required argument 'file' (pos 1) not found

3- fo = open(fileDir)---只读

4- 路径的写法

1- fileDir = 'G:/pyTest1.txt'

2- fileDir2 = 'G:\pyTest1.txt'

3- fileDir3 = r'G:\pyTest1.txt'--取消转义

5- 路径

1- 绝对路径--根目录开始的 G:/pyTest1.txt

2- 相对路径 ./当前位置 ../ 上一级

6- 读模式

0- 如果该文件不存在会报错!

1- fo = open(fileDir,'r') === fo = open(fileDir)

2- fo.tell()---获取文件指针位置,返回当前指针下标,默认为0

3- fo.read(2)----读2个字符

4- fo.read()--读全部内容

5-文件中的换行是2个长度 \n ‘a\nb’---字符串中是一个

6- fo.close()--关闭文件

7- 移动文件指针位置: seek()

1- 0模式---绝对位置模式,从0开始---配套 ‘r’ fo.seek(1,0)

2- 1模式---当前位置开始移动 fo.seek(移动的位数,模式1)

移动的位数 正数:向后移 负数:向前移

前提:python3 一定在'rb'模式下---二进制模式

3- 2模式---从尾部位置开始---rb--- 读二进制(bin)

1- fo.seek(-1,2)

2- 移动的位数 正数:向后移 负数:向前移

案例:

fileDir = 'G:/pyTest1.txt'

fo = open(fileDir,'rb')

print('读前',fo.tell())

print(fo.read(2))

print('读后',fo.tell())

fo.seek(2,2)

print('移动后',fo.tell())

8- readline() 读取一行

1- 该方法返回是 print(type(fo.readline()))-- <class 'str'>

2- 文件指针会做相应的偏移

9- readlines() 读取所有行

1- 该方法返回是 print(type(fo.readlines()))-- <class 'list'>

区别:

1- fo.read()----返回str

2- fo.readlines()---返回是list---每一行是里面一个元素!

2- fo.read().splitlines()---返回list,而且去掉换行符

7- 文件写模式:

1- fo = open(fileDir,'w')

2- 如果该路径下的文件存在---会清空!

3- 如果该路径下的文件不存在---会新建!

4- 在pycharm里面,你执行了fo.write('123')--可以直接写进去

5- fo.write('123')--返回值---写的字符长度

6- fo.flush() 刷新写入文件,语法上无此操作不会写入磁盘,但pycharm优化会写入

7- fo.close() 关闭文件会强行写入文件

8- 追加模式 a

1- 只是为了在文件末尾追加内容而打开文件

9- With open 方式

1- with open(fileDir) as rFile:----rF = open(fileDir)

2- 可以省略fo.close()

3- 操作多个文件

3-windows 文件里面的换行--\r\n--2个byte linux文件换行--'\n'---1个byte

fileDir = r'G:\pyTest1.txt' #'G:\pyTest.txt'

file_object = open(fileDir,'r') #有返回值

print(file_object)

print(file_object.tell()) #获取文件指针位置---默认是0

读操作

# print(type(file_object.read(2))) #--str类型--<class 'str'>

print(file_object.read()) #全部元素

print(file_object.tell())

file_object.close() #关闭文件---不能读写

seek---移动文件指针

print(file_object.read(2))

print(file_object.tell())

file_object.seek(1,0) #0 模式--都是从绝对零点开始的--文件--r模式

file_object.seek(2,2) #2 模式--需要以‘rb’模式打开文件

print(file_object.tell())

print(file_object.readlines()) #读所有行返回是--list,‘\n’也读取出来

print(file_object.read().splitlines()) #去换行符用的---split('\n')

文件写操作

1- 如果文件不存在--会新建 2- 文件存在----会清空打开

fileDir = r'G:\pyTest1.txt' #'G:\pyTest.txt'

file_object = open(fileDir,'w') #有返回值

file_object.write('123456\nABCDE\nabcde') #字符串---类型

print(file_object.read(2)) #写模式是不能读文件--io.UnsupportedOperation: not readable

file_object.flush() #刷新写入---建议不要省略

file_object.close()

pycharm优化---只要需要结束--会自动写入

with open(fileDir,'r') as rFile,open('路径','w') as wFile:

好处: 1- 可以打开多个文件,2- 可以省略close()

rFile.read()

wFile.write('')

print('里面代码块---写文件操作代码!')

lesson_12——算法

print('---lesson12_算法---')

知识点汇总:

1-嵌套循环

2-列表生成式:

1-aftertax=[one*0.9 for one in beforetax]

2-aftertax=[循环体 for语句]

3-alist.sort(默认正序) alist.sort(reverse=True)

4-冒泡排序:

1-确认要排序的对象:alist--升序 / 降序

2-思维分解:

1-每一次找一个最大值

1- 找7 -对比 len -1

1- [3,1,7,0]

2- [1,3,7,0]

3- [1,3,0,7]

2- 找3 -对比 len -2 2次

1- [1,3,0,7]

2- [1,0,3,7]

3- 找1 -对比 1次

1- [1,0,3,7]

2- [0,1,3,7]

alist = [3,1,7,0]

for i in range(0,len(alist)-1): # 0 1 2--左含右不含---找最大值的次数

for j in range(0 , len(alist)-i-1): #对比次数

if alist[j] > alist[j+1]:

alist[j],alist[j+1] = alist[j+1],alist[j]

print(alist)

5-思维扩展

1- alist = [3,1,7,0]

2- 每一次找一个最小值,不使用---min()------假设法

3- data = [] ------ data.append(最小值)

** 每一次找到最小值要记得删除!

a ,b = 3,4

核心思路:

1- 每一次找一个较大值

2- 相邻元素比较!

1- 找3次较大值---剩下的一个不就是最小值

2- 过程:

1- 找第1个较大值---8---交换了3次

1- [8,2,6,0] ---- 8 和 2 比较 -- 8大- 交换位置--[2,8,6,0]

2- [2,8,6,0] ---- 8 和 6 比较 -- 8大- 交换位置--[2,6,8,0]

3- [2,6,8,0] ---- 8 和 0 比较 -- 8大- 交换位置--[2,6,0,8]

2- 找第2个较大值---6---交换了2次

1- [2,6,0,8] ---- 2 和 6 比较 -- 6大- 交换位置--[2,6,0,8]

2- [2,6,0,8] ---- 6 和 0 比较 -- 6大- 交换位置--[2,0,6,8]

3- 找第3个较大值---2---交换了1次

1- [2,0,6,8] ---- 2 和 0 比较 -- 2大- 交换位置--[0,2,6,8]

嵌套循环的运行逻辑:

1- 先执行外层循环1次---

2- 全部执行完内循环所有--第1次

3- 再执行外循环 第2 次

4- 全部执行完内循环所有--第2 次

5- 再执行外循环 第3 次

6- 全部执行完内循环所有--第3 次

boys = ['Mike','Jack','Tom']

girls = ['Lisa','Linda','Mary']

for girl in girls: #3次

for boy in boys: #3次

print(girl,boy)

99乘法表 9行9列

for i in range(1,10): # 1--9 行

for j in range(1,i+1): #列

print('{}x{}={}'.format(j,i,i*j),end='\t') #在同一行里面的列不需要换行

print() #换行

beforetax=[10000,15000,8000,4000,5000]

for one in beforetax:

aftertax.append(one*0.9)

aftertax=[int(one*0.9) for one in beforetax if one > 8000] #列表生成式

print(aftertax)

def foo():

print ('in foo()')

bar()

def bar():

print ('in bar()')

foo()

def t2(para):

para = 3

b= 'a'

t2(b)

info = 'A girl come in, the name is Jack, level 955'

def getName(srcStr):

name = srcStr.split(',')[1].split(' ')[-1].strip()

return name

return srcStr.split('the name is')[1].split(',')[0].strip()

print(getName(info))

lesson_13_14——作业讲解

print('---编程题1---')

需求分析:

1- 程序开始的时候提示用户输入学生年龄信息 格式如下:

Jack Green , 21 ; Mike Mos, 9;

2- 用户输入的规则:

1-学生信息之间用分号隔开(分号前后可能有不定数量的空格),

2-每个学生信息里的姓名和年龄之间用逗号隔开(逗号前后可能有不定数量的空格)

3- 按格式打印:

学生的姓名要求左对齐,宽度为20,年龄信息右对齐,宽度为2位,不足前面补零

Jack Green : 21;

思路分解:

1- 获取每一个学生的名字、年龄

1- 接收数据

info = input() #--字符串

2- 提取数据---每一个学生的 名字、年龄

1- tempList = info.split(';') #---列表-['Jack Green , 21 ','Mike Mos, 9']

2- 每一个学生的信息就是列表的里面每一个元素 Jack Green , 21

3- for 循环去遍历

for one in tempList:

4- 再进行切割 alist=one.split(',')

5- 名字 = alist[0].strip()

6- 年龄 = alist[1].strip()

3- 验证数据

print(name,age)

2- 按照要求格式化输出

'{:<20},{:0>2};'.format(name,age)

'''

1- 获取学生的信息--Jack Green , 21 ; Mike Mos, 9;

info = input('请输入学生的信息:')

2- 把每一个学生的信息分开-----每一个学生的信息之间是以 ; 隔开

stuList = info.split(';') #返回是list---里面每一个元素就是一个学生的信息

print(stuList)

3- 遍历列表

for one in stuList:

if one == '': # 读取空信息则不需要处理---结束本次

continue

4- 非有效的信息则跳过

if ',' not in one: #----one.count(',') == 1:

print('缺少---- , ')

continue

获取每一行的名字、年龄

tempList = one.split(',') #------保证这个切点存在

name = tempList[0].strip()

age = tempList[1].strip()

5-验证数据

print(name,age)

6-格式化输出

print('{:<20}:{:0>2};'.format(name,age))

print('---编程题2---')

需求分析:

1- log---一个多行字符串---第一列:文件类型 第二列:大小

2- 统计相同文件的大小

思路分解:- 目标导向

1- 获取每一行的信息里面的 文件类型、文件大小

1- 理解多行---每一行有 \n

2- 获取每一行信息 lineList = log.split('\n')-----返回列表

3- 对列表每一行的元素进行遍历

for line in lineList:

print(line)------每一行信息

4- 对每一行进行获取类型--大小

temp = line.split('\t')

fileType = temp[0].split('.')[1]

fileSize = temp[1].strip()

5- 验证数据

print(fileType,fileSize)

2- 统计相同类型文件

1- 判断是否同类型:累加文件大小

resList = [] # [[类型1,大小1],[类型2,大小2],[类型3,大小3]]

1- 拆分多行字符串--让每一行变成独立的一个字符串

lineList = log.split('\n') #----list-----第一列和第二列之间是制表符 \t

print(lineList)

2- 去获取每一行的信息----for

for line in lineList:

if line == '': #不执行空行的操作

continue

3- 说明都是有效行信息

4- 对每一行进行获取类型、大小

tempList = line.split('\t') #---list

fileType = tempList[0].split('.')[1]

fileSize = int(tempList[1].strip())

print(fileType,fileSize)

5-统计----累加文件大小---int

inFlag = False #初始化---一开始认为不存在

6- 先去匹配,这个结果列表 resList 有没有存在该类型

[[类型1,大小1],[类型2,大小2],[类型3,大小3]]

for one in resList:

if fileType == one[0]: #匹配上

one[1] += fileSize

inFlag = True #表明已经累加完成---存在

break

7-for --做匹配类型---执行for完成后--匹配结束

如果没有匹配上类型:

if inFlag == False:

是不是需要 resList 新增该类型

resList.append([fileType,fileSize]) #[['jpeg' ,169472],['json' ,1036]]

print(resList)

print('---编程题3---')

需求分析:

请定义一个函数 mySort,参数为一个列表,参数列表中的元素都是整数.

mySort 函数需要将参数列表中的元素按从小到大排序,最终返回一个新的list。

思路分解:

1. 创建一个新的列表newList

2. 先找出所有元素中最小的,append在newList里面

3. 再找出剩余的所有元素中最小的,append在newList里面

4. 依次类推,直到所有的元素都放到newList里面

alist = [8,3,0,9,1]

def mySort(inList):

newList = []

while len(inList) > 0: #循环次数

minData = min(inList) #找最小值

inList.remove(minData) #删掉最小值

newList.append(minData) #最小值增加到新列表里面去

return newList

print(mySort(alist))

alist.sort()

def mySort(inList):

newList = []

while len(inList) > 0:

#假设法--第一个元素最小

minData = inList[0]

# minIndx = 0

# idx = 0 #总列表的下标

#验证假设

for one in inList:

if minData > one: #假设的最小值不是最小--更新最小值

minData = one #-更新最小值

# minIndx = idx

# idx += 1 #下标更新

newList.append(minData)

inList.remove(minData)

# del inList[minIndx]

return newList

print(mySort([1,8,9,0,2]))

print('---编程题4---')

需求分析:

1- 格式如下----一个file1.txt文件里面内容

name: Jack ; salary: 12000

name :Mike ; salary: 12300

2- 格式规范

每个员工一行,记录了员工的姓名和薪资,

每行记录原始文件中并不对齐,中间有或多或少的空格

3- 计算出所有员工的税后工资(薪资的90%)和扣税明细,

1- 存入新的文件 file2.txt中

2- tax表示扣税金额和income表示实际收入,注意扣税金额和实际收入要取整数

3- 输出格式

name: Jack ; salary: 12000 ; tax: 1200 ; income: 10800

思路分解:

rfileDir = 'G:/pyTest1.txt'

wFileDir = 'G:/pyTest2.txt'

xinxi = ''

with open(rfileDir) as rFile,open(wFileDir,'w') as wFile:

1- 读取文件---名字、工资

info_list = rFile.read().splitlines() #list---

for line in info_list:

if ';' in line: #有分号才处理

temp = line.split(';') #[ 'name: Jack ',' salary: 12000' ]

if ':' in temp[0] and ':' in temp[1]:

name = temp[0].split(':')[1].strip()

salary = temp[1].split(':')[1].strip()

if salary.isdigit():

salary = int(salary)

2 - 写入文件 - --按一定格式写

outStr = 'name:{:<6};salary:{:<6};tax:{:<6};income:{:<6};'.format(name,salary,int(salary0.1),int(salary0.9))

else:

outStr = 'this line salary is not digit'

else:

outStr = 'this line has not :'

else:

outStr = 'this line has not ;'

wFile.write(outStr + '\n')

lesson_15——字典

print('---lesson_15-字典---')

'''

1-字典的定义:

1-dict1 = {} # --空字典

2-type({}) # -----<class 'dict'>

3-字典名 = {键名:值,键名2:值2}

2-字典的优势:

1-描述清楚

2-查找方便

3-扩展性好

3-字典的特性:

1-它没有下标---不是序列类型!

2-一种映射--map

3-字典是mutable 的---可以改变

4-字典的常用操作----dict1 = {'name': 'Jack', 'age': 40}

1-获取值:dict1['name']

2-改变值:'name'已经存在,dict1['name'] = 'tom'

3-新增:这个键名不存在:dict1['weight'] = 160

1-python 3 ----从尾部增加

2-python 2 ----无序的

4-如果需要获取的值对应的键不存在,那么-- KeyError: 'weight'

5-字典内部元素不存在顺序的概念

6-字典内部不会存在相同键名

7-相同键名时候,后面的值会覆盖前面的值---唯一的

8-键、值的类型:

1-键的类型:

1-数值

2-字符串

3-元组

4-列表---*不能作为键--TypeError: unhashable type: 'list'

5-字典---*不能作为键

6-键一定是哈希类型--不能改变的!

2-值的类型:任意类型

9-键值对一定要成对出现吗?--键值对

10- 'name' in dict1 --- bool

5-字典的技巧:

1-删除字典元素:

1-del 字典名[键]

2- pop---有返回值

3-没有remove()方法

4- dict1.clear() 与 dict1 = {} 不等价,地址不一样

6-字典的遍历:

1-for one in students: # ---one 依次取-key 键

2-students.items()---键值对

1- [(键1,值1),(键2,值2)]

3- for name , info in students.items():

7-len()--键值长度

8-d.clear()---只改变该地址的内容

9-d = {}----重新指向

10-得到所有的key返回在类List中 students.keys() ['jack', 'tom']

11-得到所有的value返回在类List中 students.values()

12-增加元素---d.update({4:'4',5:'5'})

'''

字典的定义要求:

1- 键:可以的类型:字符串、int 、float、元组、

不可以是:列表、字典 ---TypeError: unhashable type: 'list'---不可以改变的类型

2- 值:任意类型

'''

注意:

1- 键名是不是唯一的?---唯一的 后者覆盖前者

2- 字典能不能改变元素的值?--可以的--dict1[键名] = 值--这个键是存在的--修改值

3- 怎么在字典里增加元素?---可以的--dict1[键名] = 值--这个键不存在的--新增键值对

4- 怎么获取字典元素值:--print(dict1['name'])

5- 这个键不存在,获取这个键的值会怎么样?--KeyError: 'age'

6- 我们怎么在字典的指定位置增加元素?--做不到

1- 没有必要---字典是无序的-----不通过下标获取值

2- python3语法----增加键值对在--尾部

python2语法----增加键值对在--随机

7- 删除键值对:

1- del dict1['name']

2- dict1.pop('name')

3- 没有remove()方法

8- 字典是无序的--没有下标!!!

'''

del dict1['name']

dict1.pop('name')

print(dict1[0])

dict1['age'] = 20

print(dict1['age'])

print(dict1)

students = {

'Mike': {

'age':25,

'height':180,

'weight':80,

'nickname':'Mi'

},

'tom': {

'age':18,

'height':180,

'weight':80,

'nickname':'mm'

}

}

print(students)

import pprint #完美打印

pprint.pprint(students)

print(students['tom'])

print('age' in students) #判断键是否在字典里

for one in students: #字典的遍历其实就是对键的遍历

print(students[one])

print(students.items())

键值对---[(键,值),(键,值)]--类列表

不能直接使用下标--TypeError: 'dict_items' object does not support indexing

通过for遍历

for one in students.items():

print(one)

print(list(students.items())[1]) #转换成列表--再下标取值---(键,值)--键值对

for name ,info in [(1,2),(3,4)]: #students.items()---键值对

print(name,info)

print(students.keys()) #所有键

print(students.values()) #所有值

print(students.items()) #所有键值对

d = {1:'1',2:'2'}

d.update({4:'4',5:'5'})

print(d)

passWord = {'admin':'123321','user1':'123456'}

userName = ''

psw = ''

if (userName,psw) in passWord.items():

print('该组账号密码存在!')

lesson_16——函数

print('---lesson_16 函数---')

'''

1-变量的作用域:

0-全局变量,可以在函数内部被引用!

1-局部变量:函数内部--只能在函数里面使用,在函数外部不能使用

2-全局变量:函数外

3-在函数内部修改全局变量:global x

2-缺省参数:

1-在函数定义的时候,给了初始值 def func(a,b,c=0)

2-c这个参数,在函数调用的时候可以不传值,就是默认值;如果传,那就是传的值

3-定义参数的时候,可缺省不能放在必填参数前面

SyntaxError: non-default argument follows default argument

4- 案例:

def func(score,sex='M'):

if score > 60:

print(sex+'--及格!')

else:

print(sex+'--不及格')

func(80,'W')

3-可变数量参数:(必填,可缺省,可变数量)----写法正确--print

1-数量可变!:可以n个 也可以0个

2- def calc(*numbers):

3-type(numbers)

4-如果传值的是元组/列表--用*展开!

5-封装成一个元组形式

6-建议定义顺序: 必填,可缺省,可变数量

4-关键字可变数量:--dict

1-关键字

2-可变数量

3-**d

4-是个字典类型

5-传值:键值对

6-传入字典: **字典---展开 {1:100,2:200} 1=100 2=200 一定是str

7- **展开的话,key一定是string----TypeError: func() keywords must be strings

总结:必填参数、缺省参数、可变参数和关键字参数

'''

'''

1- 必填一定在可缺省的前面--语法规定

2- 缺省参数:

1- 不给实参---就默认初始值

2- 传实参----实际传入的参数

3- 必填参数在可缺省的前面!!!

def print(self, *args, sep=' ', end='\n', file=None)

file, mode='r'

3- 可变数量参数:

1- 数量可变--数量不定!!!--可以是N个

2- * 的作用

1- 在形参里面---包装一个元组

2- 在实参里面---展开作用

4- 关键字可变数量:

1- **d

2- func(1,2,3,4,5,6,"abc",**dict1)---dict1的key都是str

'''

'''

1- 必填一定要在可缺省前面:SyntaxError: non-default argument follows default argument

2- 当def getSum(a,inList,b=100,*c) 我们需要将一个字典进行传入,那么这个字典的keys

一定是str,否则 TypeError: getSum() keywords must be strings

'''

全局变量:在一个.py(模块)里面定义一个变量---从这一行开始,后面都可以使用这个变量

x = 2

def func():

global x #声明一下

x = 9

#局部变量:在函数内部的变量---它只能在函数内部使用

print ("this x is in the func----1:-->",x)

func()

print ("--------------------------")

print ("this x is out of func:-------2>",x)

'''

1- 必填参数:def func(a,b,c): #函数定义的时候只是变量名--必填形参

2- 可缺省参数:def func(a,b,c=100)

1- 概念:

1- 函数调用的时候传入的一个c的值---以实际传入的为准

2- 函数调用的时候不传入的一个c的值---以默认(定义的时候)的为准

2- 作用:

1- 方便省事

2- 这个默认值一般考虑到调用者大部分时候的---使用的场景(值)

3- 位置:

可缺省参数----在必填参数之后

3- 可变数量参数:

1- 引入:虽然可缺省的参数可以代码带来省事效果--但是有个数的限制

2- 解决当前困境:

成功案例:print(没有个数限制)

3- 定义:

1- def func(a,*args,c=3):

2- 封装成一个元组形式

3- 数量可以是 0 个

4- * 封装元组的效果

4- 定义格式:

建议:定义函数参数的时候:必填、可变数量、缺省参数

5- 函数调用--如果需要传入一个元组类型数据:

  • 元组 --展开的效果

4- 关键字可变数量参数:

1- 概念:

1- def func(a,b,c=3,*kwargs):

2- ** 封装一个---字典(键-值)

3- 传入形式: 变量 = 值

2- 作用:

如同字典的效果:方便查找

3-函数调用时候我们需要把一个完整字典传进去

**字典名:键名一定是字符串

汇总:定义字典的键名一般都用字符串

'''

def func(a,b,c=3,*kwargs): #函数定义的时候只是变量名--必填形参

print(a,b,c,kwargs)

dict1 = {'name':'tom',10:200} # ** 把键名作为变量名,值还是值 键 = 值

func(1,2,3,c= 4,name = '')

def func(a, b, c=0, *args, **kw):

print(a,b,c,args,kw)

func(1,2,5,3)

def addSum(start=1,end=100,step=1): #默认是1 ---必填参数一定在缺省参数前面

i = start

sumData = 0

while i <= end:

sumData += i

i += step

return sumData

print(addSum(10,200))

print('hello',end='***')

print('hello','world',sep='---')

lesson_17——模块+包

print('-----lesson—17+18_模块+包----')

'''

1-模块的概念:---试卷

一个.py文件就称之为一个模块(Module)

2-包的概念:---试卷夹

这些组织存放模块文件的目录,我们称之为包(Package)

3-模块与包的优势:

1-方便别人调用

2-避免同名变量/函数

3-每个模块中的变量名作用域只在本模块中

4-模块的使用:

1-同一个包内的调用:

1- import 模块名--- 相当于执行了一遍导入的模块

2-使用变量/函数:模块名 . 函数/变量

3-如果我们模块名很长---as 取别名

from 包.模块名 import 函数 as 别名

1-优势:可以减少字符长度

2-避免导入对象的冲突,避免同时导入多个模块里面有同名函数,出现覆盖情况

4-from 模块名 import 函数/变量

from mathFunction import sumFunNew

sumFunNew(1,2)

导入全部:from mathFunction import * === import mathFunction

优势:可以节省字符长度描述

劣势:导一个用一个,如果还有需求,增加下

区别:

1- import xx---全部导入

2- from 模块 import 函数/变量 ,指定内容导入,如果后期有增加的话,再增加imnport后面的内容

2-不同包的调用:

1- import testP.pTest

testP.pTest.func()

3-init.py模块:

1-初始化模块

2-只要你调用这个包,那么该包的init.py,就会被执行!

5-标准库的使用:

1-不需要程序员去 import---直接使用变量和函数---print / open() / len()

2-import time

print(time.strftime("%Y_%m_%d %H:%M:%S"))

3- 标准库

1- 内置类型& 内置函数--直接使用,不需要import

2- 内置模块--要使用import

案例:

from datetime import date

now = date.today()

print(now)

6-模块搜索规则:

1-import sys----sys.path

2- sys.path---第一个是空地址----当前目录

7-增加路径:

1-import sys---临时的

sys.path.append('g:/file')

2-cmd--set PYTHONPATH=g:/file

8- pip install命令行安装第三方库pip install selenium -i https://pypi.douban.com/simple/

9- pip list 查看安装的第三方库

'''

import mathFunction # 执行了这个整个模块mathFunction---

mathFunction.sumFun(1,2)

import newP.sonP.sonPT as sP

sP.son()

from mathFunction import sumFun,version

sumFun(1,2)

print(version)

from mathFunction import sumFun

from newP.newPTest import sumFun as SF

SF(1,2)

sumFun(1,2)

'''

import time

print(time.strftime("%Y_%m_%d %H:%M:%S"))

import sys

sys.path.append("H:\") #临时

print(sys.path)

print('当前模块名是:',name) # name 模块的名字

if name == 'main': # 如果在当前模块运行的话

print('我是调试代码--自己单独运行可以使用--其他调用者用不了!')

lesson_18——Pycharm使用技巧

('2017-03-13 11:50:09', 271, 131),

1-思路分析:

1- 获取每一行有效数据:时间、课程id、学生id

1- 分析文件类型--txt

2- 打开文件---open('路径') with open('路径') as fo:

3- 获取每一行信息

linesList = fo.read().splitlines() # 去换行符-----返回list类型-

每一个元素是一行内容---字符串

4- 对每一行进行遍历---对每一行进行提取数据

for line in linesList:

line--------"('2017-03-13 11:50:09', 271, 131),"

对这个每一行数据进行一个简单的处理:替换()

5- 已经是每一行相对比较简洁的数据 --"2017-03-13 11:50:09, 271, 131,"

6- 对每一行进行split(',') --返回是list 4个元素--前3个有效,

7- 进行去空格处理下-strip()--- 以下三个元素--字符串

checkTime 2017-03-13 11:50:09

lessonId 271---int()

ueserId 131---int()

2- 按格式统计输出

1- 先组织格式:

1- 每一行的课程id 时间 组合成--字典

{'lessonid': 271,'checkintime':'2017-03-13 11:50:09'}

2- infoDict = {'lessonid': lessonId,'checkintime':checkTime}

2- 统计:同一个学生id

1- if userId not in resDict:

新增该学生id---键值对----

2- else

append

3- 返回

'''

def func():

print('step1')

print('step2')

print('step3')

print('step4')

fileDir = r'G:\0005_1.txt'

def putInfoToDict(fileName):

resDict = {} #保存结果的字典

1- 打开文件

with open(fileName) as fo:

2- -读所有行

linesList = fo.read().splitlines()

for line in linesList:

line = line.replace('\t','').replace('(','')\

.replace(')','').replace("'",'').replace(';',',')

tempList = line.split(',')

checkTime = tempList[0].strip()

lessonId = int(tempList[1].strip())

userId = int(tempList[2].strip())

组织格式

infoDict = {'lessonid':lessonId,'checkintime':checkTime}

统计--汇总

func()

if userId not in resDict: #增加 学生id :[] 键值对

resDict[userId] = [] #增加键值对的

resDict---{ 131:[{第一次也要进去}]}

resDict[userId].append(infoDict)

return resDict

res = putInfoToDict(fileDir)

import pprint

pprint.pprint(res)

import logging

log_file = "G:/basic20190429.log"

logging.basicConfig(filename=log_file, level=logging.DEBUG)

logging.debug("this is a debugmsg!")

logging.info("this is a infomsg!")

logging.warn("this is a warn msg!")

logging.error("this is a error msg!")

logging.critical("this is a critical msg!")

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 主题:变量名和字符串 变量:变量名就像我们现实社会中的名字,把一个值赋值给一个名字时,ta会存储在变量名中,称之为...
    米果_57d5阅读 192评论 0 0
  • 主题:变量名和字符串 变量:变量名就像我们现实社会中的名字,把一个值赋值给一个名字时,ta会存储在变量名中,称之为...
    米果_57d5阅读 117评论 0 1
  • 基础语法: 一.冯诺依曼体系架构: 五大部件: CPU:包括运算器和控制器,CPU只和一件设备,内存打交道。 运算...
    vampire6阅读 270评论 0 1
  • 41,memoryview内存视图,不复制内容前提下再数据结构间共享内存这里只演示简单用法,这个内建函数还是很复杂...
    派神教主阅读 244评论 0 0
  • 编程就是你发指令给电脑,让它帮你处理数据。数据处理过程中,需要临时存在内存上,直到最终结果存回硬盘。临时使用内存区...
    吴加明阅读 492评论 0 0