Python多次在编程语言流行指数PYPL中排名第一。由于其代码可读性和更简单的语法,它被认为是有史以来最简单的语言。NumPy、Pandas、TensorFlow等各种AI和机器学习库的丰富性是Python的核心需求之一。如果您是数据科学家或AI/机器学习的初学者,那么Python是开始您的旅程的正确选择。这次小F带大家一起探索Python编程的一些基础知识,简单却非常实用。目录数据类型变量列表集合字典注释基本功能条件语句循环语句功能异常处理字符串操作正则表达式▍1。数据类型数据类型是一种可以存储在变量中的数据规范。解释器根据变量的类型为变量分配内存。以下是Python中的各种数据类型。▍2。变量变量是存储数据值的容器。变量可以有短名称(如x和y)或更具描述性的名称(age、carname、total_volume)。Python变量命名规则:变量名必须以字母或下划线字符开头变量名不能以数字开头变量名只能包含字母数字字符和下划线(A-z、0-9和_)变量名区分大小写(age、age、Age,和AGE是三个不同的变量)var1='HelloWorld'var2=16_unuseful='Singleusevariables'输出如下。▍3.列表列表(List)是一个有序的、可变的集合,允许重复的成员。它可能不是同质的,我们可以创建一个包含不同数据类型的列表,例如整数、字符串和对象。?>>>公司=["苹果","谷歌","tcs","埃森哲"]>>>打印(公司)['苹果','谷歌','tcs','埃森哲']>>>companies.append("infosys")>>>print(companies)['apple','google','tcs','accenture','infosys']>>>print(len(companies))5>>>打印(公司[2])tcs>>>打印(公司[-2])埃森哲>>>打印(公司[1:])['google','tcs','埃森哲','infosys']>>>print(companies[:1])['apple']>>>print(companies[1:3])['google','tcs']>>>公司。remove("infosys")>>>print(companies)["apple","google","tcs","accenture"]>>>公司。pop()>>>print(companies)["apple","google","tcs"]▍4、集合集合(Set)是一个无序、无索引的集合,没有重复的成员。用于从列表中删除重复条目。还支持并、交、差等多种数学运算。>>>set1={1,2,3,7,8,9,3,8,1}>>>print(set1){1,2,3,7,8,9}>>>set1.add(5)>>>set1.remove(9)>>>print(set1){1,2,3,5,7,8}>>>set2={1,2,6,4,2}>>>>print(set2){1,2,4,6}>>>print(set1.union(set2))#set1|set2{1,2,3,4,5,6,7,8}>>>print(set1.intersection(set2))#set1&set2{1,2}>>>print(set1.difference(set2))#set1-set2{8,3,5,7}>>>print(set2.difference(set1))#set2-set1{4,6}▍5.字典字典是作为键值对的项目的可变无序集合。与其他数据类型不同,它以[key:value]对格式保存数据,而不是存储单个数据。此功能使其成为映射JSON响应的最佳数据结构。>>>#example1>>>user={'用户名':'粉丝','年龄':20,'mail_id':'codemaker2022@qq.com','电话':'18650886088'}>>>print(user){'mail_id':'codemaker2022@qq.com','age':20,'username':'Fan','phone':'18650886088'}>>>print(user['age'])20>>>forkeyinuser.keys():>>>print(key)mail_idageusernamephone>>>forvalueinuser.values():>>>print(value)codemaker2022@qq.com20Fan18650886088>>>foriteminuser.items():>>>print(item)('mail_id',codemaker2022@qq.com')('age',20)('username','Fan')('phone','18650886088')>>>#example2>>>user={>>>'用户名':"Fan",>>>'social_media':[>>{>>>'名字':'Linkedin',>>>'url':"https://www.linkedin.com/in/codemaker2022">>>},>>>{>>>'名称':"Github",>>>'url':"https://github.com/codemaker2022">>>},>>>{>>>'名称':"QQ",>>>'url':“https://codemaker2022.q.com”>>>}>>>],>>>'contact':[>>>{>>>{>>>'mail':[>>>]@sina.com",>>>"codemaker2022@qq.com">>>],>>>'电话':'18650886088'>>}>>]>>>}>{'username':'Fan','social_media':[{'url':'https://www.linkedin.com/in/codemaker2022','name':'Linkedin'},{'url':'https://github.com/codemaker2022','name':'Github'},{'url':'https://codemaker2022.qq.com','name':'QQ'}],'contact':[{'电话':'18650886088','mail':['mail.Fan@sina.com','codemaker2022@qq.com']}]}>>>print(user['social_media'][0]['url'])https://www.linkedin.com/in/codemaker2022>>>print(user['contact'])[{'phone':'18650886088','mail':['mail.Fan@sina.com','codemaker2022@qq.com']}]▍6.Comment单行注释,以井号(#)开头,后面是一条消息,在行尾结束#定义用户年龄age=27dob='16/12/1994'#定义用户的生日多行注释,用特殊引号(""")括起来,可以把消息放在多行中。"""PythonTipsThisisamultilinecomment"""▍7.基本函数print()函数在控制台打印提供的消息.此外,您可以提供文件或缓冲区输入作为在屏幕上打印的参数。print(object(s),sep=separator,end=end,file=file,flush=flush)print("HelloWorld")#printsHelloWorldprint("Hello","World")#打印HelloWorld?x=("AA","BB","CC")print(x)#prints('AA'','BB','CC')print("Hello","World",sep="---")#printsHello---Worldinput()函数用于从控制台收集用户输入。请注意,input()会将您键入的任何内容转换为字符串。因此,如果您将年龄作为整数值提供,但input()方法将其作为字符串返回,您将需要手动将其转换为整数。>>>name=input("Enteryourname:")Enteryourname:Codemaker>>>print("Hello",name)HelloCodemakerlen()可以检查对象的长度。如果输入字符串,则可以获取指定字符串中的字符数。>>>str1="HelloWorld">>>print("Thelengthofthestringis",len(str1))Thelengthofthestringis11str()用于将其他数据类型转换为字符串值。>>>str(123)123>>>str(3.14)3.14int()用于将字符串转换为整数。>>>int("123")123>>>int(3.14)3▍8、条件语句条件语句是用来根据特定条件改变程序流程的代码块。这些语句仅在满足特定条件时执行。在Python中,我们使用if、if-else、循环(for、while)作为条件语句,根据某些条件改变程序的流程。if-else语句。>>>num=5>>>if(num>0):>>>print("正整数")>>>else:>>>print("负整数")elif语句。>>>name='admin'>>>ifname=='User1':>>>print('Onlyreadaccess')>>>elifname=='admin':>>>print('Havingreadandwriteaccess')>>>else:>>>print('Invaliduser')Havingreadandwriteaccess▍9.循环语句循环是一种条件语句,它重复某些语句(在其主体中)直到满足某个条件。在Python中,我们通常使用for和while循环。循环。>>>#遍历列表>>>companies=["apple","google","tcs"]>>>forxincompanies:>>>print(x)applegoogleetcs>>>#遍历字符串>>>forxin"TCS":>>>print(x)TCSrange()函数返回一个数字序列,可以用作for循环控制。它基本上需要三个参数,其中第二个和第三个是可选的。参数是起始值、终止值和步数。步数是每次迭代循环变量的增量值。>>>#使用range()函数循环>>>forxinrange(5):>>>print(x)01234>>>forxinrange(2,5):>>>print(x)234>>>forxinrange(2,10,3):>>>print(x)258我们还可以使用else关键字在循环结束时执行一些语句。在循环结束时提供else语句以及需要在循环结束时执行的语句。>>>forxinrange(5):>>>print(x)>>>else:>>>print("finished")01234finishedwhile循环。>>>count=0>>>while(count<5):>>>print(count)>>>count=count+101234我们可以在while循环的最后使用else,类似于for循环,当条件执行某些语句时为假。>>>count=0>>>while(count<5):>>>print(count)>>>count=count+1>>>else:>>>print("Countisgreaterthan4")01234Count大于4▍10。函数函数是用于执行任务的可重用代码块。在代码中实现模块化并使代码可重用是非常有用的。>>>#Thisprintsapassedstringintothisfunction>>>defdisplay(str):>>>print(str)>>>return>>>display("HelloWorld")HelloWorld▍11.异常处理甚至一条语句在句法上可能是正确的,但执行起来可能不正确。这些类型的错误称为异常。我们可以使用异常处理机制来避免此类问题。在Python中,我们使用try、except和finally关键字在代码中实现异常处理。>>>defdivider(num1,num2):>>>try:>>>returnnum1/num2>>>除了ZeroDivisionErrorase:>>>print('Error:Invalidargument:{}'.format(e))>>>最后:>>>print("finished")>>>>>>print(divider(2,1))>>>print(divider(2,0))finished2.0Error:Invalidargument:division通过zerosfinishedNone▍12。字符串操作字符串是用单引号或双引号(',")括起来的字符集合。我们可以使用内置的方法对字符串进行各种操作,例如连接、切片、修剪、反转、大小写更改和格式化,例如split()、lower()、upper()、endswith()、join()和ljust()、rjust()、format()。>>>msg='HelloWorld'>>>print(msg)HelloWorld>>>print(msg[1])e>>>print(msg[-1])d>>>print(msg[:1])H>>>print(msg[1:])elloWorld>>>print(msg[:-1])HelloWorl>>>print(msg[::-1])dlroWolleH>>>print(msg[1:5])ello>>>print(msg.upper())HELLOWORLD>>>print(msg.lower())helloworld>>>print(msg.startswith('Hello'))True>>>print(msg.endswith('World'))True>>>print(','.join(['Hello','World','2022']))Hello,World,2022>>>print(''.join(['Hello','World','2022']))HelloWorld2022>>>print(“HelloWorld2022”.split())['Hello','World','2022']>>>print("HelloWorld2022".rjust(25,'-'))--------HelloWorld2022>>>print("HelloWorld2022".ljust(25,'*'))HelloWorld2022*********>>>print("HelloWorld2022".center(25,'#'))#####HelloWorld2022####>>>name="Codemaker">>>print("Hello%s"%name)HelloCodemaker>>>print("Hello{}".format(name))HelloCodemaker>>>打印("Hello{0}{1}".format(name,"2022"))HelloCodemaker2022▍13。正则表达式importregex模块,importrere.compile()使用该函数创建一个Regex对象。将搜索字符串传递给search()方法。调用group()方法返回匹配的文本。>>>importre>>>phone_num_regex=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')>>>mob=phone_num_regex.search('我的号码是996-190-7453。')>>>print('找到的电话号码:{}'.format(mob.group()))找到的电话号码:996-190-7453>>>phone_num_regex=re.compile(r'^\d+$')>>>is_valid=phone_num_regex.search('+919961907453.')是None>>>print(is_valid)True>>>at_regex=re.compile(r'.at')>>>strs=at_regex.findall('戴帽子的猫坐在垫子上。')>>>print(strs)['cat','hat','sat','mat']好的,BenThis分享期结束。有兴趣的朋友可以自己实践学习。以上就是本次分享的全部内容。觉得文章还不错的话,请关注公众号:Python编程学习圈,每日干货分享,发送“J”还能收到海量学习资料,涵盖Python电子书和教程,数据库编程、Django、爬虫、云计算等。或者去编程学习网了解更多编程技术知识。
