Python基本语法

 

#(注释语句)

在Python中可以直接使用IDEL界面进行一系列的科学运算

>>>print(11+12)    #加法>>>print(11-12)    #减法>>>print(11*12)    #乘法>>>print(11/12)    #除法>>>print(11//12)   #地板除法>>>print(11**12)   #幂运法

结果:

23-11320.9166666666666666666603138428376721

相比其它高级语言而言,还可以进行高位的运算

>>>print(9999999999*9999999999)

 

数据类型

1.整型int,浮点型float,字符串型str

2.类型转换:int(),float(),str()

#含有int的字符串可以转成int

>>>s1='123'>>>i1=int(s1)

#含有float的字符串可以转换成float

>>>s1='1.23'>>>f1=float(s1)

#int和float都可以转换成str

3. 获取类型信息

(1)type()

>>>type(f1) #结果:<class 'float'>

(2)isinstance(参数1,参数2)

>>>isinstance(f1,float) #结果:True>>>isinstance(f1,int)   #结果:False

 

常用操作符

算术操作符:+,-,*,/,%,**,//

比较操作符:<,<=,>,>=,==,!=

逻辑运算符:and,or,not

 

print语句:

Print(‘Hello World’)

Hello World

Print(‘Hello’+ ‘ World’)

Hello World

print( ‘Hello’*3)

Hello Hello Hello

 

 

input语句:

>>>input('提示输入语句:\n')#提示输入语句>>>输入语句

 

单双三引号用法是一样的,都表示字符串

其中单引号和双引号的用法一样,区别是

Eg.假如在‘’中使用‘’会出现以下情况

 

正确做法是:

 

这样就可以省去转义的步骤;

同理,双引号的效果也类似,我们可以用‘单包双,双包单’口诀。

三引号可以表示多行(有\n的字符串)

 

 

原始字符串:

str=r’C:\now’(保留原始字符串)

>>>str=r'C:\now'

str=’C:\now’(\遇到n进行回车)

>>>str='C:\now'

 

dir(参数) :列出参数中所有的方法

 

>>> dir(list)['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 

help(参数):列出方法的使用说明

 

>>> help(list.append)Help on method_descriptor:append(self, object, /)    Append object to the end of the list.

 

 

#在Python中,对空格和缩进有很严格的要求,在同一列开始的语句属于一个语句块

 

if-else语句:

>>>if 条件表达式:>>>  print('条件为真时执行的语句')>>>else :>>>  print('条件为假时执行的语句')

可以使用elif代替else if

>>>bool1=False>>>bool2=True>>>bool3=True>>>if bool1:>>>  print('执行语句1')>>>elif bool2:>>>  print('执行语句2')>>>elif bool3:>>>  print('执行语句3')                            #执行语句2

 

(补充)在其它编程语言中else总是与最近的一个if匹配,而python是根据缩进进行匹配的

 

条件表达式:x if 条件 else y

>>>small=x if x<y else y

相当于

>>>x,y=4,5>>>if x<y:>>>  small=x>>>else:>>>  small=y

 

 

断言(assert):assert 条件

当关键字assert后边的条件为假的时候,程序自动崩溃并抛出异常

>>> assert 3>4
Traceback (most recent call last):  File "<pyshell#23>", line 1, in <module>    assert 3>4AssertionError

 

一般用于置入检查点,当需要确保程序中的某个条件一定为真才能让程序正常工作。

 

while语句:

>>>while boolean:>>>  print('条件为真时执行的循环体') 

 

range([start,]stop[,step=1]):

作用:生成一个左闭右开区间的数字序列。常与for循环搭配使用

 

>>> list(range(2,10))

 

[2,3,4,5,6,7,8,9]

其中第三个参数step表示步长

>>> list(range(2,10,2))

 

[2,4,6,8]

 

for语句:

for each in 迭代器:

循环体

>>>for temp in range(1,3):>>>  print(temp)

 

List列表:         

#标志性符号:中括号

创建一个普通列表:

>>>list1=[1,2,3,4,5]    #长度为5

创建一个混合列表:

>>>list2=[1,'one',3.00]

创建一个空列表:

>>>empty=[]<class 'list'>

 

1.向列表添加元素 append()

>>>list1.append(6)>>>len(list)             #长度为6

   注意:不能同时追加两个元素

>>>list1.append(6,7)        #是不允许的Traceback (most recent call last):  File "<pyshell#1>", line 1, in <module>    list1.append(2,3)TypeError: append() takes exactly one argument (2 given)

 

2.用列表扩展列表extend()

>>>list1.extend([1,'one',3.00])[1, 2, 3, 4, 5, 1, 'one', 3.0]

或者

>>> list1.extend(list2)>>> list1[1, 2, 3, 4, 5, 1, 'one', 3.0]

 

3.向列表中插入一个元素insert()

>>> list1.insert(0,0) #第一个参数为插入元素位置,第二个参数为插入元素>>> list1[0, 1, 2, 3, 4, 5, 1, 'one', 3.0]

 

4.从列表中获取元素

>>>list1[7]'one'

 

5.从列表删除元素 

    remove()两个相同删除第一个

>>>list1.remove('one')

    del

>>>del list1[7]    #删除一个元素>>>del list        #删除整个列表

    pop()默认取出最后一个元素,也可以指定位置删除

>>>list1.pop()3.0>>>list1.pop(1)1

 

6.列表分片(slice)

>>>list1=[0,1,2,3,4,5,6,7,8,9]>>> list1[:]      #取出所有元素[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> list1[5:][5, 6, 7, 8, 9]>>> list1[:5][0, 1, 2, 3, 4]   #左闭右开区间>>> list1[4:6][4, 5]

最大的好处是可以获取一个列表的拷贝(copy)而不与原来的列表共享地址(浅拷贝)

list2=list1[:]

 

7.列表常用的操作符

    比较:

>>>list1=[123]>>>list2=[234]>>>list1>list2False>>>list1=[123,456]>>>list2=[234,123]>>>list1>list2False        #默认比较第一个元素

        算术运算:

>>>list1=['你好']>>>list2=['朋友']>>>list3=list1+list2['你好','朋友']>>>list3*3['你好','朋友','你好','朋友','你好','朋友']

        in 和 not in:

>>>'你好' in list3True>>>'不好' in list3False>>>'不好' not in list3True#注意:>>>list4=[1,[2,3],4]>>>2 in list4False

        count()统计元素出现次数

>>>list1=[10,53,12,51,10,10]>>>list1.count(10)3

        index()

>>>list1.index(10)0>>>list1.index(10,4,5)  #指定范围查找元素10的索引4

        reverse()

>>>list1=[10,53,12,51,10,10]>>>list1.reverse()[10,10,51,12,53,10]

        sort()

>>>list1=[10,53,12,51,13,22]>>>list1.sort()      #从小到大排,默认使用归并排序[10,12,13,22,51,53]>>>list1.sort(reverse=True)[53,51,22,13,12,10]  #从大到小排

 

tuple元组(不可变的列表)         

#标志性符号:逗号

 创建和访问一个元祖:

>>>tuple1=(0,1,2,3,4,5,6,7,8)(0,1,2,3,4,5,6,7,8)>>>tuple1[1]1>>>tuple1[5:](5,6,7,8)>>>tuple1[:5](0,1,2,3,4,)#不能修改元组的元素>>> tuple1[1]=2Traceback (most recent call last):  File "<pyshell#23>", line 1, in <module>    tuple1[1]=2TypeError: 'tuple' object does not support item assignment#--------------------------区别--------------------------#>>>temp=(1)<class 'int'>>>>temp=(1,)<class 'tuple'>>>>temp=1,<class 'tuple'>>>>temp=()            #创建空元组<class 'tuple'>>>>8*(8,)(8,8,8,8,8,8,8,8)

更新和删除一个元组:

#更新元组>>>tuple1=('One','Two','Four','Five')>>>tuple1=tuple1[:2]+('Three',)+tuple1[2:]('One', 'Two','Three',  'Four', 'Five')#删除一个元组>>>del tuple1

 

 

字符串(不可变)的各种内置方法

>>>str1='life is happy.'>>>str1[2]i>>>str1[:8]life is >>>str1[:8]+'un'+str1[8:]'life is unhappy.'

    capitalize() 首字母大写

>>>str1='oh'>>>str1.capitalize()      #返回一个新字符串!'Oh'

    casefold()全部变小写

>>>str1='OH'>>>str1.casefold()        #返回一个新字符串!'oh'

    center(width)

>>> str1='OH'>>> str1.center(20)'         OH         '

    count(sub[,start[,end]])返回sub在字符串出现的次数,start和end表示范围

>>>str1='Liliwolitili'>>>str1.count('li')3

  startswith(sub[,start[,end]])检查字符串是否以sub子字符串开始,是返回True 

      endswith(sub[,start[,end]])检查字符串是否以sub子字符串结束,是返回True

>>>str1='Liliwolitili'>>>str1.endswith('li')True>>>str1.endswith('Li')False

    expandtabs([tabsize=8])将制表符\t转换为空格,默认空格数是8

>>> str1='I\tlove\tyou!'>>> str1.expandtabs()'I       love    you!'

     find(sub[,start[,end]])

找不到返回-1,找到返回索引

     rfind(sub,[,start[,end]])

与find类似,从右边开始查找

     index(sub[,start[,end]])

与find类似,区别是index()找不到时抛出异常

>>>str1='Liliwolitili'>>>str1.find('wi')-1>>>str1.find('wo')4

    isalnum()     

所有字符都是字母或数字返回True

    isalpha()      

所有字符都是字母返回True

    isnumeric()  

所有字符都是数字返回True

    isdecimal()   

只包含十进制数字返回True,否则返回False

    islower()       

字符都是小写则返回True

    issupper()     

字符都是大写则返回True

    isspace()       

只包含空格,返回True

    istitle()          

字符串是标题,返回True(首字母为大写,其余小写)

>>> str1='Title Paper'>>> str1.istitle()True

    join(sub)            

以字符串作为分隔符,插入到sub中所有的字符之间

>>> str1='Hello'>>> str1.join('00')'0Hello0'>>> str1.join('00000')'0Hello0Hello0Hello0Hello0'

    ljust()

左对齐

    strip([chars])

删除前边和后边的所有空格,可以定制删除的字符

>>> str1='ohhhhooooooo'>>> str1.strip('o')'hhhh'

    lstrip()

去掉左边所有空格

    rstrip()

去掉右边所有空格

>>> str1='      Hello'>>> str1.lstrip()'Hello'

    lower() 

字符串的所有大写字符变为小写字符

    upper()

字符串的所有小写字符变为大写​

    partition(sub)

找到子字符串sub,把字符串分成一个3元组

    rpartition(sub)

与partition类似,只不过从右边开始查找

>>> str1='helloworld'>>> str1.partition('low')('hel', 'low', 'orld')

    replace(old,new,[,count])

把字符串中的old子字符串替换成new子字符串,count指定则替换不超过count次

>>> str1='hello world'>>> str1.replace('world','guy')'hello guy'

    split(sep=None,maxsplit=-1)

不带参数默认是以空格为分隔符切片字符串,如果maxsplit参数有设置,则仅风格maxsplit个子字符串,返回切片后的子字符串拼接的列表

>>> str1='hello this world'>>> str1.split()['hello', 'this', 'world']>>> str1.split('l')['he', '', 'o this wor', 'd']

    splitlines([Keepends])

按照'\n'分隔,返回一个包含各行作为元素的列表,若Keepends有指定,返回前Keepends行

    swapcase()

翻转字符串中的大小写

>>> str1='MvP'>>> str1.swapcase()'mVp'

    title()

返回标题化的字符串

>>> str1='Tile jia Tks'>>> str1.title()'Tile Jia Tks'

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值