当前位置: 首页 > 后端技术 > Python

python3参考秘籍-附PDF下载

时间:2023-03-26 00:14:04 Python

介绍Python作为一种优秀的开源语言,以其在数据分析和机器学习方面的优势受到了越来越多的人的喜爱。据说小学生就要开始学Python了。Python的优秀之处在于可以安装很多非常强大的lib库来进行非常强大的科学计算。老实说,有什么方法可以快速学会这么优秀的语言吗?没错,这篇文章就是python3的基本秘籍。看完这篇秘籍,你就可以掌握python3的核心思想了。文末有PDF下载链接。欢迎下载。Python的主要数据类型python中的所有值都可以看作是一个对象Object。每个对象都有一个类型。以下是最常用的三种类型:Integers(整数)整数类型,如:-2、-1、0、1、2、3、4、5浮点数(float)浮点数类型,如as:-1.25,-1.0,--0.5,0.0,0.5,1.0,1.25Strings字符串类型,如:"www.flydean.com"注意字符串是不可变的,如果我们使用replace()或join()方法,一个新的字符串被创建。除此之外,还有列表、字典和元组三种类型。列表用方括号表示:a_list=[2,3,7,None]元组用括号表示:tup=(1,2,3)或者直接用逗号表示:tup=1,2,3Python有3种方式在python中创建一个String,可以用单引号、双引号和三引号表示。基本操作my_string=“Let'sLearnPython!”another_string='一开始可能看起来很难,但你可以做到!'a_long_string='''是的,你甚至可以通过一些练习来掌握覆盖不止一行的多行字符串'''也可以使用print输出:print("Let'sprintoutastring!")字符串连接字符串可以使用加号连接。string_one="我在读"string_two="一本好书!"string_three=string_one+string_two注意加号连接不能连接两个不同的类型,比如String+integer,如果这样做会报如下错误:TypeError:Can'tconvert'int'objecttostrimplicitlyStringCopyString可以使用*进行复制操作:'Alice'*5'AliceAliceAliceAliceAlice'也可以直接使用print:print("Alice"*5)数学运算看python中的数学运算符:运算符含义示例**指数运算2**3=8%余数22%8=6//整数除法22//8=2/除法22/8=2.75*乘法3*3=9-减法5-2=3+加法2+2=4内置-在函数中我们学习了python的内置函数print(),接下来我们再来看几个其他常用的内置函数:Input()函数input用于接收用户输入,所有输入都以字符串形式存储:name=input("嗨!你叫什么名字?")print("很高兴认识你"+name+"!")age=input("你多大了")print(“原来,你已经是”+str(age)+“岁,”+name+“!”)结果如下:Hi!你叫什么名字?“吉姆”很高兴见到你,吉姆!你今年多大?25所以,你已经25岁了,Jim!len()函数len()用于表示字符串、列表、元组和字典的长度。例如:#testinglen()str1=“希望您喜欢我们的教程!”print(“字符串的长度为:”,len(str1))输出:字符串的长度为:35filter()filter从列表、元组、字典等可遍历对象中过滤对应元素:ages=[5,12,17,18,24,32]defmyFunc(x):ifx<18:returnFalseelse:returnTrueadults=filter(myFunc,ages)forxinadults:print(x)Function在python中,函数可以是被视为用于执行特定功能的一段代码。我们使用def来定义函数:defadd_numbers(x,y,z):a=x+yb=x+zc=y+zprint(a,b,c)add_numbers(1,2,3)注意函数内容应以空格或制表符分隔。传递参数函数可以传递参数,并且可以通过命名参数赋值来传递参数:#用参数定义函数defproduct_info(productname,dollars):print("productname:"+productname)print("Price"+str(dollars))#Callfunctionwithparametersassignedasaboveproduct_info("WhiteT-shirt",15)#Callfunctionwithkeywordargumentsproduct_info(productname="jeans",dollars=45)ListList用来表示有序的数据集合。与String不同,List是可变的。看一个列表的例子:my_list=[1,2,3]my_list2=["a","b","c"]my_list3=["4",d,"book",5]此外,也可以使用list()转换元组:alpha_list=list(("1","2","3"))print(alpha_list)添加元素我们使用append()添加元素:beta_list=["apple","banana","orange"]beta_list.append("grape")print(beta_list)或使用insert()在特定索引处添加元素:beta_list=["apple","banana","orange"]beta_list.insert("2grape")print(beta_list)从我们使用remove()的列表中删除一个元素beta_list=["apple","banana","orange"]beta_list.remove("apple")print(beta_list)或使用pop()删除最后一个元素:beta_list=["apple","banana","orange"]beta_list.pop()print(beta_list)或使用del删除特定元素:beta_list=["apple","banana","orange"]delbeta_list[1]print(beta_list)mergelist我们可以使用+来合并两个列表:my_list=[1,2,3]my_list2=["a","b","c"]combo_list=my_list+my_list2combo_list[1,2,3,'a','b','c']创建嵌套列表我们也可以在列表中创建列表:my_nested_list=[my_list,my_list2]my_nested_list[[1,2,3],['a','b','c']]列表排序我们使用sort()对列表进行排序:alpha_list=[34,23,67,100,88,2]alpha_list.sort()alpha_list[2,23,34,67,88,100]列表切片我们使用[x:y]作为列表切片:alpha_list[0:4][2,23,34,67]修改列表的值我们可以通过索引改变列表的值:beta_list=["apple","banana","orange"]beta_list[1]="pear"print(beta_list)output:['apple','pear','cherry']列表遍历我们使用for循环遍历列表:forxinrange(1,4):beta_list+=['fruit']print(beta_list)listcopy可以使用copy()复制列表:beta_list=["apple","banana","orange"]beta_list=beta_list.copy()print(beta_list)或使用list()复制:beta_list=["apple","banana","orange"]beta_list=list(beta_list)print(beta_list)list高级操作list还可以进行一些高级操作:list_variable=[xforxiniterable]number_list=[x**2forxinrange(10)ifx%2==0]print(number_list)元组的英文名称是Tuples。与列表不同,元组不能修改,元组的速度会提高。比列表快。查看如何创建元组:my_tuple=(1,2,3,4,5)my_tuple[0:3](1,2,3)tupleslicenumbers=(0,1,2,3,4,5,6,7,8,9,10,11,12)print(numbers[1:11:2])output:(1,3,5,7,9)元组可以转换为列表,使用list和tuple相互转换:x=("apple","orange","pear")y=list(x)y[1]="grape"x=tuple(y)print(x)dictionary字典是键值集合。python中的键可以是字符串、布尔或整数类型:Customer1={'username':'john-sea','online':false,'friends':100}创建字典这里有两种创建空字典的方法dictionary:new_dict={}other_dict=dict()或这样的初始赋值:new_dict={"brand":"Honda","model":"Civic","year":1995}print(new_dict)访问字典元素我们像这样访问字典:x=new_dict["brand"]或使用dict.keys()、dict.values()、dict.items()来获取要访问的元素。修改字典的元素我们可以这样修改字典的元素:#Changethe“year”to2020:new_dict={“brand”:“Honda”,“model”:“Civic”,“year”:1995}new_dict[“year”]=2020遍历字典看看如何遍历字典:#打印字典中所有键名forxinnew_dict:print(x)#打印字典中所有值forxinnew_dict:print(new_dict[x])#loopbothkeysandvaluesforx,yinmy_dict.items():print(x,y)if语句和其他语言一样,python也支持基本的逻辑判断语句:equals:a==bNotEquals:a!=bLessthan:abGreaterthanorequalto:a>=b看看python中if语句的用法:if5>1:print("That'sTrue!")If语句也可以嵌套:x=35ifx>20:print("Abovetwenty,")ifx>30:print("andalsoabove30!")elif:a=45b=45ifb>a:print("b大于a")elifa==b:print("a和b相等")ifelse:ifage<4:ticket_price=0elifage<18:ticket_price=10else:ticket_price=15ifnot:new_list=[1,2,3,4]x=10ifxnotinnew_list:print("'x'isn'tonthelist,sothisisTrue!")Pass:a=33b=200ifb>a:passPythonloopPython支持两种类型的循环,for和whileforloopsforxin"apple":print(x)for可以遍历list,tuple,dictionary,string等whileloop#printaslongasxislessthan8i=1whilei<8:print(x)i+=1breakloopi=1whilei<8:print(i)ifi==4:breaki+=1ClassPython是一种面向对象的编程语言,几乎所有的元素都可以看作是一个对象。对象可以看作是类的实例。接下来,我们看一下该类的基本操作。创建类classTestClass:z=5在上面的例子中,我们定义了一个类并指定了它的一个属性z。CreateObjectp1=TestClass()print(p1.x)也可以给类赋不同的属性和方法:classcar(object):"""docstring"""def__init__(self,color,doors,tires):""“构造函数”“”自我。颜色=颜色自我。门=门本身。tires=tiresdefbrake(self):"""停车"""return"Braking"defdrive(self):"""Drivethecar"""return"I'mdriving!"创建一个子类每个类都可以被子类化if__name__=="__main__":car=Car("yellow",2,4,"car")car.brake()'汽车类正在缓慢制动!'car.drive()"我开的是一辆黄色的车!"异常Python内置了异常处理机制来处理程序中的异常信息。内置异常类型AttributeError—属性引用和赋值异常IOError—IO异常ImportError—导入异常IndexError—索引超出范围KeyError—字典中的键不存在KeyboardInterrupt—Control-C或Delete,报异常NameError—本地或notfoundglobalnameOSError—系统相关错误SyntaxError—解释器异常TypeError—类型操作错误ValueError—内置操作参数类型正确,但值不正确。ZeroDivisionError—除以0错误异常处理使用try、catch处理异常:my_dict={"a":1,"b":2,"c":3}try:value=my_dict["d"]exceptKeyError:print("Thatkeydoesnotexist!")处理多个异常:my_dict={"a":1,"b":2,"c":3}try:value=my_dict["d"]exceptIndexError:print("Thisindexdoesnotexist!")exceptKeyError:print("Thiskeyisnotinthedictionary!")except:print("Someotherproblemhappened!")try/exceptelse:my_dict={"a":1、"b":2,"c":3}try:value=my_dict[“a”]exceptKeyError:print(“AKeyErroroccurred!”)else:print(“Noerroroccurred!”)结尾附上Python3秘籍PDF版:python3-cheatsheet.pdf本文已收录在http://www.flydean.com/python3-cheatsheet/最流行的解读,最深刻的干货,最简洁的教程,很多小你不知道的技能等你来发现!欢迎关注我的公众号:《程序那些事儿》,懂技术,更懂你!