模块1:Python基础
变量
就是为了存东西,为了以后调用。
var.py:
#!/usr/bin/envpython name="dickhu" name2=name name='paochege' print('mynameis',name,name2) 执行结果: my name is paoche ge dick hu
解析:name和name2指向相同的内存地址
变量的规则:
- 变量名只能是字母、数字或下划线的任意组合
- 变量名的第一个字符不能是数字
- 以下关键字不能声明为变量名
['and','as','assert','break','class','continue','def','del','elif','else','except','exec','finally','for','from','global','if','import','in','is','lambda','not','or','pass','print','raise','return','try','while','with','yield']
Python 2 如果使用utf-8的话,需要加上
#-*-coding:utf-8-*-
用户交互程序
name=input('Name:') age=input('Age:') job=input('Job:') salary=input('Salary:') info='''=============info%s============== name:%s age:%s job:%s salary:%s '''%(name,name,age,job,salary) print(info) 执行结果: Name:huwei Age:29 Job:IT Salary:20000 =============info huwei ============== name:huwei age:29 job:IT salary:20000
解析:
数据类型:
%s 的s表示string
%d 的d表示digit
%f 的f表示float
注意:默认所有输入的都是string
for循环及作业要求
作业:编写登陆接口:
- 输入用户名和密码
- 认证成功后显示欢迎信息
- 输错三次后锁定

huwei
maria

huwei,123456 jacky,121212 sunny,123123 maria,321321 alex,qawsed

import sys,os count = 0 while count < 3: usr = input("Pls input your username:") with open('log','r+') as f1,open('lock','r+') as f2: lock_list = f2.readlines() for lock_line in lock_list: lock_line = lock_line.strip('\n') if usr == lock_line: sys.exit('user %s has been locked,pls contact the admin!' % usr) user_list = f1.readlines() for user_line in user_list: username, password = user_line.strip("\n").split(",") if usr == username: pwd = input("Pls input your password:") if pwd == password: print("Welcome %s login this system successfully!"%usr) sys.exit() else: print("Your username or password is not correct!") count +=1 print("count:", count) continue else: pass else: print("user %s has been locked,pls contact the admin!" %usr) with open('lock', 'r+') as f2: f2.write(usr + "\n")
作业:多级菜单
三级菜单
可依次选择进入各子菜单
所需新知识点:列表,字典

#!/usr/bin/envpython #-*- coding:utf-8 -*- China = { "华北":{ "北京":{ "东城区":{"安定门街道", "北新桥街道", "东四街道"}, "西城区":{"西长安街街道", "广安门外街道", "椿树街道"}, "朝阳区":{"和平街街道", "将台街道", "左家庄街道"}, }, }, "东北":{ "黑龙江":{ "哈尔滨市":{ "道里区", "南岗区", "香坊区"}, "大庆市":{ "萨尔图区", "龙凤区", "大同区"} }, }, "华东":{ "江苏":{ "南京市":{ "鼓楼区", "建邺区", "白下区"}, "苏州市":{ "相城区", "工业园区", "吴中区"} } } } while True: for f in China: print(f) choice = input("请选择行政区域或选择按q退出:") if choice in China: while True: for i in China[choice]: print(i) choice2 = input("请选择省份区域或选择按m返回上一层:") if choice2 in China[choice]: while True: for s in China[choice][choice2]: print(s) choice3 = input("请选择市级区域或选择按n返回上一层:") if choice3 in China[choice][choice2]: while True: for t in China[choice][choice2][choice3]: print(t) choice4 = input("返回上一层,请按b):") if choice4 == "b": break elif choice3 == "n": break elif choice2 == "m": break elif choice == "q": break
copy()
name3 = name1.copy() print(name1) print(name3) 执行结果: ['huwei', 'songpan', 'chenyan', 'geping', 'songpan'] ['huwei', 'songpan', 'chenyan', 'geping', 'songpan']
拷贝:
浅拷贝copy()
name = "huwei songpan chenyan geping songpan" name1 = name.split(" ") name1[1] = ["cat","dog","ele"] name2 = name1.copy() print("原来的列表:",name1) print("拷贝自原来的列表:",name2) name1[0] = "胡伟" name1[1][0] = "CAT" print("修改了赋值胡伟原来的列表:",name1) print("拷贝自原来的列表:",name2) 执行结果: 原来的列表: ['huwei', ['cat', 'dog', 'ele'], 'chenyan', 'geping', 'songpan'] 拷贝自原来的列表: ['huwei', ['cat', 'dog', 'ele'], 'chenyan', 'geping', 'songpan'] 修改了赋值胡伟原来的列表: ['胡伟', ['CAT', 'dog', 'ele'], 'chenyan', 'geping', 'songpan'] 拷贝自原来的列表: ['huwei', ['CAT', 'dog', 'ele'], 'chenyan', 'geping', 'songpan']
浅拷贝的三种方式:
Import copy Person = ['name',['saving',100]] P1[0] = 'dick' P2[0] = 'jacky' P1=person[:] P2 =person[:] P1[1][1] = 50 P1 =copy.copy(person) P2 =person[:] P3 =list(person)
应用场景:
联合账号 import copy person=['name',['saving',100]] p1=person[:] p2=person[:] p1[0]='dick' p2[0]='jacky' p1[1][1]=50 print(p1) print(p2) 执行结果: ['dick', ['saving', 50]] ['jacky', ['saving', 50]]
如果需要完整的独立的copy()
深拷贝deepcopy()
import copy name = "huwei songpan chenyan geping songpan" name1 = name.split(" ") name1[1] = ["cat","dog","ele"] # name2 = name1.copy() name2 = copy.deepcopy(name1) print("原来的列表:",name1) print("拷贝自原来的列表:",name2) name1[0] = "胡伟" name1[1][0] = "CAT" print("修改了赋值胡伟原来的列表:",name1) print("拷贝自原来的列表:",name2) 执行结果: 原来的列表: ['huwei', ['cat', 'dog', 'ele'], 'chenyan', 'geping', 'songpan'] 拷贝自原来的列表: ['huwei', ['cat', 'dog', 'ele'], 'chenyan', 'geping', 'songpan'] 修改了赋值胡伟原来的列表: ['胡伟', ['CAT', 'dog', 'ele'], 'chenyan', 'geping', 'songpan'] 拷贝自原来的列表: ['huwei', ['cat', 'dog', 'ele'], 'chenyan', 'geping', 'songpan']
元组与购物车程序练习
元组和列表差不多也是一组数,只不过它一旦创建,便不能再修改,所以又叫只读列表。
names = ('dick','jacky','maria')
它只有2个方法,一个是count,一个是index。
程序练习:
程序:购物车程序
需求:
1.启动程序后,让用户输入工资,然后打印商品列表
2.允许用户根据商品编号购买商品
3.用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4.可随时退出,退出时,打印已购买商品和余额
product_list = [['IPhone',8800],['Mac Pro',12388],['CoCo',44],['Mouse',181],['Bike',800]] salary = input("Pls input your salary:") if salary.isdigit(): salary = int(salary) count = 0 for list in product_list: item,price = list count +=1 print(str(count)+'.'+item,price) shopping_list = [] while True: user_choice = input('Pls input you need what to buy with number:') if user_choice.isdigit(): user_choice = int(user_choice) if user_choice < len(product_list)+1 and user_choice > 0: buy_list = product_list[(int(user_choice) - 1)] if salary - buy_list[1] > 0: new_item = product_list[product_list.index(buy_list)][0] salary -= buy_list[1] print('added [%s] to your shopping cart,and your current balance is \033[31;1m%s\033[0m'%(new_item,salary)) shopping_list.append(buy_list) else: print('Your balance not enough') else: print("product code [%s] is not exist"%user_choice) elif user_choice == "q": print("have bought below:") for p in shopping_list: print(p) print("Your balance:",salary) break else: print("Invalid syntax !")
本周作业-购物车优化
购物车:
用户入口:
1.商品信息存在文件里
2.已购商品,余额记录
商家入口:
1.key添加商品,修改商品价格
上节内容回顾
列表
1.可以增删改查
2.列表可以嵌套,列表,字符串,字典任何形式
元组
1.只读
字符串
1.字符串是无法修改的,即使赋值重新修改,内存地址也不一样
字典
1.无序的:通过key来找值,不需要通过下标
2.可以嵌套,列表,字符串,字典任何形式
共同点
列表和元组都是有序的
程序练习
程序1:实现简单的shell sed替换功能
import sys find_str=sys.argv[1] replace_str=sys.argv[2] for line in f: if find_str in line: line=line.replace(find_str,replace_str) f_new.write(line) f.close() f_new.close()
字符转编码操作
ASCII编码:255,最少占1个字节(只能存英文或特殊字符,不能存中文)
Unicode字符集:最少占2个字节(无论英文还是中文)
UTF-8编码:可变长字符编码,英文,占1个字节;中文,占3个字节
获取系统默认的编码: import sys print(sys.getdefaultencoding()) Utf-8的"你好"转换成gbk的"你好" S = "你好" S_to_unicode = S.decode("utf-8") S_to_gbk = S_unicode.encode("gbk") Print(s_to_gbk) #-*-coding:utf-8-*- s="你好" print(s) print(s.encode(),type(s.encode())) 执行结果: 你好 b'\xe4\xbd\xa0\xe5\xa5\xbd' <class 'bytes'> 解析: 1.Python3默认encode不但会转为相应的编码还会转为bytes类型 2.头声明编码: #-*- coding=utf-8 -*- 说明python文件为utf-8编码,但是字符串还是unicode
#-*-coding:utf-8-*- s="你好" print(s,type(s)) print("GBK:",s.encode("gbk")) print("UTF-8:",s.encode("utf-8")) print("GB2312:",s.encode("gb2312").decode("gb2312")) print("UTF-8:",s.encode(),type(s.encode())) GBK: b'\xc4\xe3\xba\xc3' #显示为GBK的bytes类型的编码格式 UTF-8: b'\xe4\xbd\xa0\xe5\xa5\xbd' #显示为UTF-8的bytes类型的编码格式 GB2312: b'\xc4\xe3\xba\xc3' #显示为GB2312的bytes类型的编码格式 UTF-8: b'\xe4\xbd\xa0\xe5\xa5\xbd' <class 'bytes'> #显示为UTF-8的bytes类型的编码格式
将bytes decode后就转换为字符串
作用域、局部与全局变量
def change_name(name): print("name before:",name) name="Dick Hu" #这个函数就是这个变量的作用域 print("name after:",name) name="dick" change_name(name) print(name) 执行结果: name before: dick name after: Dick Hu dick
总结:函数的结果只在函数里面生效,局部变量只在局部有效
company="Digital China" #全局变量 def change_name(name): company="Adtec China" #局部变量 print("name before:",name,company) name="DickHu" print("name after:",name) name="dick" change_name(name) print(name) print(company) 执行结果: name before: dick Adtec China name after: Dick Hu dick Digital China
如果非得将局部变量在全局生效,可以在局部变量里加上global关键字,但是可能会出问题,工作中最好不要这么用!
name=["dick","jacky","maria","medoza"] def change_name(name): name[0]="DickHu" print("insidefunc",name) change_name(name) print(name) 执行结果: inside func ['Dick Hu', 'jacky', 'maria', 'medoza'] ['Dick Hu', 'jacky', 'maria', 'medoza']
总结:
1.字符串修改只能在局部生效
2.列表、字典、集合、类都是可以在局部改全局,并在局部和全局调用(记住!)
递归
在函数内部,可以调用其他函数,如果一个函数调用自身本身,这个函数就是递归函数。
递归特点:
1.必须有一个明确的结束条件
2.每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3.递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用时通过栈(stack)这个数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回。栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)
count = 0 def cal(m): global count count +=1 print(m,count) return cal(m) cal(10) 执行结果: 10 1 … 10 997
eg:
def calc(n): print(n) if int(n/2)>0: return calc(int(n/2)) print("——>:",n) calc(20) 执行结果: 20 10 5 2 1 ——>: 1
函数式编程介绍
函数是Python内建支持的一种封装,我们通过把大段代码折成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单任务,这种分解可以称之为面向过程的程序设计。函数就是面向过程的程序设计的基本单元。
而函数"式"编程,虽然也可以归结到面向过程的程序设计,但其思想更接近于数学计算。
在计算机层次上,CPU执行的是加减乘除的指令代码,以及各种条件判断和跳转指令,所以,汇编语言是最贴近计算机的语言。
而计算则指数学意义上的计算,越是抽象的计算,离计算机硬件越远。
对应到编程语言,就是越低级的语言,越贴近计算机,抽象程度低,执行效率高,比如C语言;越高级的语言,越贴近计算,抽象程度高,执行效率低,比如Lisp语言。
函数式编就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的。
定义:
函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数。
Python对函数式编程提供部分支持,由于Python允许使用变量,因此,Python不是纯函数式编程语言。
高阶函数与作业需求
变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这个函数就称之为高阶函数。
def add(a,b,c): return c(a)+c(b) res=add(3,-6,abs) print(res) 执行结果: 9