版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Python 语法教程讲义 -第一章、python基础1、python的源程序,1.1、python的源程序,本质上就是一个特殊格式的文本,可以使用任意文本编辑软件做python开发扩展名为.py。1.2、第一个小程序 Print(“hello python”) Print(“hello word”) 在linux中运行python源程序:python 01-hellopython.py;1.3、执行python程序的三种方式:1.3.1)、python/python 3解释器/其他解释器 Python xxx.py; Python3 xxx.py1.3.2)、交互式运行python程序也就是
2、在终端中,直接运行解释器,而不需要传入文件名,在python 的shell中,直接输入终端命令。 优点:适合验证局部代码;缺点:不能保存代码,不适合大量代码文件。 操作:linux下,直接输入python进入pythonpython3的解释器shell,输入python程序。 1.01的365次方:1.01*365 /退出解释器:exit()或者ctrl+d交互式执行python程序时,推荐使用ipython,通常是我们首选的shell: 优点:自然后动补全、自动缩进、支持bash shell、内置了许多功能和函数、支持很多linux命令 操作:linux下,直接输入ipythoni pyth
3、on3进入python的解释器shell,输入python程序。 1.3.3)、集成开发环境IDE(集成了开发环境需要的所有命令); pycham是一款非常优秀的python集成开发环境,可以在window、linux、macos中使用,2、算术运算 加+、减-、乘*、除/、取整/、取余%、取幂*;3、变量 数据类型:数字型:整数、浮点数、布尔值、复数; 非数字型:字符串、列表、元组、字典 Python2.x版本整型包括:int、long。Type(z*89);3.0以后不区分,都为int;注:type函数可以查看数据类型;循环的语法:If : Else :While :For i in ra
4、nge(3):命名规范:1、只能包括字母、数字、下划线;2、只能以字母或者下划线开头;3、不能包括空格;4、不能与关键字冲突;字符串:用单引号、双引号括起来的,都是字符串; Print(“fvr”+str(age)+”fvrv”),使用str()来转换为字符串;注:1)、变量名.title(),将变量名的首字母转换成大写字母;使用+来拼接字符串;nt换行退格; 2)、删除空格,.rstrip(); 3)、print可以使用多个,分离,连续输出,但是使用,会添加空格。Print(scdc,mr) 4)、print(第0天体重为:1.format(day,height) 5)、注释单行/多行代码:
5、选中+ctrl+/ 3.1、数据类型转换 字符串转int: num=21int1=int(num)print(int1)4、列表 列表是一系列按特定顺序排列的元素组成,可以创建包含任何没有关联的元素。4.1、创建列表Bicycle=trek,rgtg,cecPrintbicycle4.2、访问、使用列表元素 bicycle=efer,cec,cprint(bicycle0.title()4.3、添加元素 末尾添加元素:.append(efvrf) 支持动态添加数据: bicycle=bicycle.append(ecece)print(bicycle)支持动态插入数据:.insert(1,ed
6、ed)4.4、删除元素 1)、删除任意位置元素 bicycle=regr,uyu,fgtghdel bicycle1print(bicycle regr, fgtgh 2)、删除任意位置元素 bicycle=regr,uyu,fgtghlastBicycle=bicycle.pop(1)print(bicycle)print(lastBicycle)regr, uyufgtgh 3)、根据值删除元素 bicycle=regr,uyu,fgtghbicycle.remove(uyu)print(bicycle) 注:remove只能删除第一个指定值的元素,需要循环判断; 4.5、元素处理 1)、
7、对元素永久性排序 按字母排序:bicycle.sort() 按字母排反序:bicycle.sort(reverse=True) 2)、对元素排序且不影响原数据: bicycle=regr,uyu,fgtghnewB=sorted(bicycle)newB=sorted(bicycle,reverse=True)print(bicycle)print(newB)4.6、列表信息 Len(bicycle)4.7、操作列表4.7.1、遍历列表 bicycles=regr,uyu,fgtghfor bicycle in bicycles: print(bicycle)regruyufgtgh4.7.2
8、、创建数字列表 1)、使用range ui=range(2,6)for b in range(1,9): print(b)print(ui) 2)、使用list将range转换为列表、指定步长number=list(range(1,9,2)print(number)3)、统计列表 max(number)min(number)sum(number) 4)、使用列表解析创建列表 squre=value*2 for value in range(1,9)print(squre)4.7.3、使用列表一部分 1)、切片 squre=list(range(1,9)num=squre2:7print(squ
9、re)print(num)3, 4, 5, 6, 72)、复制列表 squre=list(range(1,9)num=squre:4.8、元组不可变的列表称为元组4.8.1、定义元组与列表不一样的是需要使用括号来定义元组 num=(2,3,5,6,7,5,3,9)5、控制语句5.1、if语句If xxx : Xxx XxxElse: Xxx Xxx xxxxxxxx注:1)、python比较不区分大小写; 2)、使用and 和or判断多个条件 3)、使用num=er,vf,fbrb,hytif vf in num: print(OK) 检测是否包含在列表中num=er,vf,fbrb,hyti
10、f vf not in num: print(OK) if xxx: xxx elif xxx xxx5.2、while 循环5.2.1、使用break立即退出循环5.2.2、使用continue跳到开头继续判断执行5.2.3、使用while判断列表是否为空 listnew=de,gtg,rfrf,hyh,vtvtwhile listnew: print(listnew) listnew.pop()6、字典 字典包括一系列的键值对,通过键可以访问值,值可以是数字、字符串甚至字典6.1、创建字典 client=color:green,size:5print(clientcolor+*+str(c
11、lientsize)6.2、添加键值对 client=color:green,size:5clientui=newclientsize0=9print(clientcolor+*+str(clientsize)+*+clientui+*+str(clientsize0)6.3、删除键值对del clientcolor6.4、遍历字典 client=color:green,size:5clientui=newclientsize0=9for key,value in client.items():print(key:+key+-value:+str(value) 排序遍历 for key,val
12、ue in sorted(client.items(),reverse=True): print(key:+key+-value:+str(value)只遍历值for value in client.values(): print(value)遍历时过滤表中重复的元素 for value in set(client.values():7、函数: 定义:Def add(x,y):Return (x+y)调用:add(1,2)注:1)、input函数 让用户输入参数,存储在变量中,可以添加信息提示用户输入:num=input(请输入:)print(num) 2)、方法split() 以空格为分隔符
13、将字符串分拆成多个部分, 并将这些部分都存储到一个列表中。7.1、关键字实参定义:Def add(x,y):Return (x*80+y)调用:add(x=1,y=2) 7. 2、形参默认值: def addInt(x=20,y=1): 7.3、实参可选 def addInt(x=20,y=1,z=): return (x+y*199)print(addInt(x=100,y=0)7.4、返回字典 def build_person(first_name, last_name): person = first: first_name, last: last_name return person
14、7.5、字典做参数 def greet_users(names):for name in names:msg = Hello, + name.title() + !print(msg) usernames = hannah, ty, margotgreet_users(usernames)7.6、列表的副本传递给函数可以像下面这样做:function_name(list_name:) 7.7、传递任意多实参 def make_pizza(*toppings):打印顾客点的所有配料print(toppings)make_pizza(pepperoni)make_pizza(mushrooms,
15、green peppers, extra cheese)7.8、结合使用位置实参和任意数量实参 def make_pizza(size, *toppings):概述要制作的比萨print(nMaking a + str(size) +-inch pizza with the following toppings:)for topping in toppings:print(- + topping)make_pizza(16, pepperoni)make_pizza(12, mushrooms, green peppers, extra cheese)7.9、使用任意数量的关键字实参 def
16、build_profile(first, last, *user_info):创建一个字典, 其中包含我们知道的有关用户的一切profile = profilefirst_name = firstprofilelast_name = last for key, value in user_info.items():profilekey = valuereturn profileuser_profile = build_profile(albert, einstein,location=princeton,field=physics)print(user_profile)7.10、将函数导入模块
17、中 1)、导入整个模块 模块 是扩展名为.py的文件, 包含要导入到程序中的代码。 import addIntPrj /导入模块print(addIntPrj.addInt(2,4) 2)、导入函数 from addIntPrj import addIntprint(addInt(1,2) 3)、使用as 给函数指定别名 from pizza import make_pizza as mpmp(16, pepperoni)mp(12, mushrooms, green peppers, extra cheese) 4)、使用as给模块指定别名 import pizza as pp.make_p
18、izza(16, pepperoni)p.make_pizza(12, mushrooms, green peppers, extra cheese 5)、导入模块所有函数 from pizza import *make_pizza(16, pepperoni)make_pizza(12, mushrooms, green peppers, extra cheese)8、类8.1、创建类 Class 类名(): 成员 class Dog(): def _init_(self, name, age): /初始化属性 = name /self相当于thisself.age =
19、age def sit(self):print(.title() + is now sitting.)def roll_over(self):print(.title() + rolled over!)8.2、创建类的实例 class Dog(): my_dog = Dog(willie, 6) /创建类的实例 print(My dogs name is + my_.title() + .) /访问类的属性 print(My dog is + str(my_dog.age) + years old.)my_dog.sit() /调用方法my_
20、dog.roll_over()8.3、属性赋予默认值 def _init_(self, make, model, year):初始化描述汽车的属性self.make = makeself.model = modelself.year = year self.odometer_reading = 0 /赋予默认值8.4、继承 class Car(): /创建父类def _init_(self, make, model, year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_
21、descriptive_name(self):long_name = str(self.year) + + self.make + + self.modelreturn long_name.title()def read_odometer(self):print(This car has + str(self.odometer_reading) + miles on it.)def update_odometer(self, mileage):if mileage = self.odometer_reading:self.odometer_reading = mileageelse:print
22、(You cant roll back an odometer!)def increment_odometer(self, miles):self.odometer_reading += miles /创建子类 class ElectricCar(Car): def _init_(self, make, model, year):初始化父类的属性 super()._init_(make, model, year) /创建子类实例 my_tesla = ElectricCar(tesla, model s, 2016)print(my_tesla.get_descriptive_name()1)
23、、创建子类时, 父类必须包含在当前文件中, 且位于子类前面。2)、方法_init_() 接受创建Car 实例所需的信息。3)、super() 是一个特殊函数, 帮助Python将父类和子类关联起来。 这行代码让Python调用ElectricCar 的父类的方法_init_() , 让ElectricCar 实例包含父类的所有属性。 父类也称为超类 (superclass) , 名称super因此而得名。4)、给子类定义新的属性 class Car():class ElectricCar(Car):def _init_(self, make, model, year):super()._ini
24、t_(make, model, year) self.battery_size = 70 def describe_battery(self):print(This car has a + str(self.battery_size) + -kWh battery.)8.4.1、重写父类方法 对于父类的方法, 只要它不符合子类模拟的实物的行为, 都可对其进行重写。 为此, 可在子类中定义一个这样的方法, 即它与要重写的父类方法同名。 这样, Python将不会考虑这个父类方法, 而只关注你在子类中定义的相应方法; 假设Car 类有一个名为fill_gas_tank() 的方法, 它对全电动汽车
25、来说毫无意义, 因此你可能想重写它。 下面演示了一种重写方式: def ElectricCar(Car):def fill_gas_tank():print(This car doesnt need a gas tank!)8.4.2、将实例用作属性不断给ElectricCar 类添加细节时, 我们可能会发现其中包含很多专门针对汽车电瓶的属性和方法。 在这种情况下, 我们可将这些属性和方法提取出来, 放到另一个名为Battery 的类中, 并将一个Battery 实例用作ElectricCar 类的一个属性:class Car():class Battery():def _init_(self
26、, battery_size=70):self.battery_size = battery_sizedef describe_battery(self):print(This car has a + str(self.battery_size) + -kWh battery.)/电动车独特属性class ElectricCar(Car):def _init_(self, make, model, year):super()._init_(make, model, year)self.battery = Battery()my_tesla = ElectricCar(tesla, model
27、s, 2016)print(my_tesla.get_descriptive_name()my_tesla.battery.describe_battery()注:一个类里面可以包括多个类8.5、导入类 from car import Car /导入类模块my_new_car = Car(audi, a4, 2016) /创建类实例print(my_new_car.get_descriptive_name()my_new_car.odometer_reading = 23my_new_car.read_odometer()8.5.1、导入模块中的某个类单个.py文件可以包括多个类,导入模块时可
28、以只导入我们需要的类 from car import ElectricCarmy_tesla = ElectricCar(tesla, model s, 2016)print(my_tesla.get_descriptive_name()8.5.2、在一个模块中导入多个类 from car import ElectricCarmy_tesla = ElectricCar(tesla, model s, 2016)print(my_tesla.get_descriptive_name()8.5.3、导入整个模块 import car my_beetle = car.Car(volkswagen,
29、 beetle, 2016)print(my_beetle.get_descriptive_name() my_tesla = car.ElectricCar(tesla, roadster, 2016)print(my_tesla.get_descriptive_name()8.5.4、导入模块每个类 import car import *8.5.5、将一个类存储在几个模块主模块:car.py class Car():-snip分部模块:electric_car.py from car import Carclass Battery():-snip-class ElectricCar(Car
30、):-snip使用模块: from car import Carfrom electric_car import ElectricCar8.6、使用python标准库 下面来看模块collections 中的一个类OrderedDict from collections import OrderedDict favorite_languages = OrderedDict() favorite_languagesjen = pythonfavorite_languagessarah = cfavorite_languagesedward = rubyfavorite_languagesphil
31、 = pythonfor name, language in favorite_languages.items():print(name.title() + s favorite language is +language.title() + .)9、文件和异常 9.1、读取整个文件 with open(111.txt) as file_object: /使用with,可以在结束时自动关闭文件 contents = file_object.read() print(contents) 相比于原始文件, 该输出唯一不同的地方是末尾多了一个空行。 为何会多出这个空行呢? 因为read() 到达文件
32、末尾时返回一个空字符串, 而将这个空字符串显示出来时就是一个空行。 要删除多出来的空行, 可在print 语句中使用rstrip(): with open(pi_digits.txt) as file_object:contents = file_object.read()print(contents.rstrip() rstrip() 删除(剥除) 字符串末尾的空白9.1.1、文件路径file_path = C:Usersehmatthesother_filestext_filesfilename.txtwith open(file_path) as file_object:9.2、逐行读取
33、 filename = pi_digits.txt with open(filename) as file_object:for line in file_object:print(line)9.3、使用列表存储文件filename = pi_digits.txtwith open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip()readlines() 从文件中读取每一行, 并将其存储在一个列表中; 接下来, 该列表被存储到变量lines 中9.4、写
34、入文件 filename = programming.txtwith open(filename, w) as file_object: file_object.write(I love programming.)9.4.1、写入多行filename = programming.txtwith open(filename, w) as file_object:file_object.write(I love programming.)file_object.write(I love creating new games.)9.4.2、附加到文件末尾如果你要给文件添加内容, 而不是覆盖原有的内容, 可以附加模式 打开文件 filename = programming.txt with open(filename, a) as file_object:file_object.write(I also love finding meani
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 个人季度工作总结报告
- 2021 ERA 临床实践指南:肾移植候选者和受者肥胖的管理
- 2026年移动智能终端软件行业分析报告及未来发展趋势报告
- 2026年幼教玩具行业分析报告及未来发展趋势报告
- 2026年度假旅游产品行业分析报告及未来发展趋势报告
- 2026年音响设备行业分析报告及未来发展趋势报告
- 2026年异山梨醇行业分析报告及未来发展趋势报告
- 2026年苯丙酸诺龙行业分析报告及未来发展趋势报告
- 2025年十级中文考试题及答案
- 2026年数字电视专用芯片行业分析报告及未来发展趋势报告
- 2026广西梧州苍海投资集团有限责任公司招聘总会计师1人笔试模拟试题及答案解析
- 2024-2025学年四川省成都市石室联中教育集团八年级(下)期中数学试卷
- 小学科学教学中的跨学科融合创新实践研究教学研究课题报告
- 《AQ3067-2026化工和危险化学品重大生产安全事故隐患判定准则》解读
- 2026 年山东春考英语提分技巧全解
- 2026广东东莞市康复实验学校招聘18人备考题库及答案详解(各地真题)
- 2026届湖北黄冈中学等十一校高三下学期第二次联考物理试卷(含答案)
- 2026年智慧树答案【人工智能原理与技术】智慧树网课章节综合提升测试卷及答案详解(夺冠系列)
- 2026年浙江省新月联盟高三语文第二次调研模拟试卷附答案解析
- 宽宽窄窄量量看
- 冀教版七年级历史下册期中测试
评论
0/150
提交评论