python3基础语法及实例demo——数据类型

@[TOC]命名规则和关键字

1)标识符命名规范

  • 只能使用字母、数字、下划线
  • 不能以数字开头
  • 不能使用Python内置关键字

2)内置关键字,可通过keyword.kwlist查看

>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

@[TOC]常见数据类型

常用数据类型有如下8种:

数据类型示例
int(整型)a = 1
float(浮点型)a = 1.11
bool(布尔型)True,False
str(字符串)name = ‘Tony’
list(列表)[’’,{},(1,2),[]]
dict(字典){key:value}
tuple(元组)(1,3,4,“你好”)
set(集合){1,2,3,6}

@[TOC]数值运算

1)算术运算 + -* / // % **

>>> print(1+1)
2
>>> print(3.4-7)
-3.6
>>> print(4*3)
12
>>> print(4/3)
1.3333333333333333
>>> print(4/0) #除数不能为0
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    print(4/0)
ZeroDivisionError: division by zero
>>> print(5//3) #取整
1
>>> print(5%3) #模运算,取余数
2
>>> print(2**4)#幂运算
16

2)比较运算 > < >= <= == != (结果返回bool值)

>>> print(1>2)
False
>>> print(1<2)
True
>>> print(1<=2)
True
>>> print(1>=2)
False
>>> print(1==2)
False
>>> print(1!=2)
True

3).赋值运算,=,算术运算后加等号

>>> a=1
>>> a
1
>>> a += 1 #等价于 a = a+1
>>> a
2
>>> a *= 3
>>> a
6
>>> a -= 1
>>> a
5
>>> a /= 1
>>> a
5.0

4)逻辑运算 or ,and, not,结果返回bool值,用括号提升优先级

  • or 一个为真即为真
  • and 两个为真才为真
  • not 取反
>>> print(1==2 or 1<2)
True
>>> print(1==2 or 1>2)
False
>>> print(1==2 and 1<2)
False
>>> print(1!=2 and 1<2)
True
>>> print(not(1==2))
True
>>> print(not(1<2))
>>>> print((True or False) and True)
True
>>> print((True or False) and False)

5)成员运算符 in,not in,结果返回bool值

>>> print("2" in "12hello")
True
>>> print("12" in "12hello")
True
>>> print("2" not in "12hello")
False
>>> print("12" not in "12hello")
False

6)身份运算符is ,is not,结果返回bool值

>>> print(type('') is str)
True
>>> print(type([]) is not list)
False

@[TOC]字符串str

1)表示方式——引号表示字符串,

  • 单引号 ’ ’
  • 双引号 " "
  • 三引号 ‘’’ ‘’’
  • 三双引号""" “”"
>>> a = 'python'
>>> a
'python'
>>> a = "python"
>>> a
'python'
>>> a = """python"""
>>> a
'python'
>>> a = '''是的'''
>>> a

2)拼接,注意元素都是字符串才能进行拼接
① +号拼接多个字符串

>>> a = "春夏" + "秋冬"
>>> a
'春夏秋冬'

② join(),通过字符串调用,参数为列表,通过自定义字符串将列表拼接为字符串。

>>> "/".join(['2020','11','08'])
'2020/11/08'
>>> "-".join(['2020','11','08'])
'2020-11-08'

3) 换行

  • 三引号换行
  • 单引号当中 \n表示换行
>>> """
你好呀
我是Pyhon大佬
"""
'\n你好呀\n我是Pyhon大佬\n'

4)索引index,从0开始,用于获取字符串中的单个字符,格式str[index]

>>> a = "helloword"
>>> print(a[0])
h
>>> print(a[3])
l
>>> print(a[-1])
d
>>> print(a[9]) #超过索引范围报错IndexError
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    print(a[9])
IndexError: string index out of range

5)切片slice,用于获取字符串中多个字符,格式str[start🔚step],步长step默认为1,取头不取尾

>>> print(a[:]) #TODO:复制一个字符串
helloword
>>> print(a[::-1]) #TODO:倒序一个字符串
drowolleh
>>> print(a[0:2]) #取头不取尾,故只能取到索引0,1的字符
he
>>> print(a[0:2:2])
h
>>> print(a[0:-1])
hellowor
>>> print(a[0:])
helloword
>>> print(a[1:1000]) #超过切片范围就不切了,不报错
elloword
>>> print(a[1:3:0]) #步长为0报错
Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    print(a[1:3:0]) #步长为0报错
ValueError: slice step cannot be zero
>>> print(a[-1:3:1]) #start在右,end在左,step1表示从左往右,方向不一致将取不到值
>>> print(a[-1:3:-1])
drowo
>>> 

6)查找字符串
① find(),返回目标字符串中第一个字符第一次出现的位置的索引,注意空格也占索引位置

>>> a = "welcome to China"
>>> print(a.find("w"))
0
>>> print(a.find("Ch"))
11
>>> print(a.find("eee")) #找不到返回-1
-1

② index(),和find()相似,不同的是找不到字符报错

>>> a = "welcome to China"
>>> print(a.index("w"))
0
>>> print(a.index("Ch"))
11
>>> print(a.index("eee")) #找不到字符报错
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    print(a.index("eee"))
ValueError: substring not found

7)字符串其它一些常用方法
① count(),统计某个字符(串)出现次数

>>> name = "Harry Potter"
>>> print(name.count("r"))
3
>>> print(name.count("ry"))
1
>>> print(name.count("rrr"))

② replace(a,b),将字符串中旧的字符a替换为新的字符b,需要注意字符串是不可变的数据类型,调用字符串的replace()并不会修改字符串本身,除非将替换结果重新赋值到原字符串。

>>> name = "Harry Potter"
>>> print(name.replace("Ha","Vi"))
Virry Potter
>>> print(name) #name值没有改变
Harry Potter
>>> name = name.replace("Ha","Vi") #如需改变需将替换结果赋值
>>> print(name)
Virry Potter

③ TODO:split(),根据字符串中的部分字符串将原字符串切割为新的列表,作为分割标准的字符串片段将不包含在新的列表结果中。作用和join()相反,为加深印象,如下示例将两个方法放在一起对比

>>> time_string = "2020/11/08"
>>> time_list = time_string.split("/") #字符串切割得到列表
>>> print(time_list)
['2020', '11', '08']
>>> time_string2 = "-".join(time_list) #列表的字符串元素拼接得到新的字符串
>>> print(time_string2)
2020-11-08

④ upper(),所有字母大写

>>> print('Harry Potter'.upper())
HARRY POTTER

⑤ lower(),所有字母小写

>>> print('Harry Potter'.lower())
harry potter

⑥ strip(),去掉首尾边界指定字符,需要去掉的字符根据参数决定,默认去掉空格和换行符;
lstrip(),去掉左边边界指定字符;
rstrip(),去掉右边边界指定字符。

>>> string = '我是谁谁是我' 
>>>> print(string.strip("我")) #去掉s左右边界字符
是谁谁是
>>> print(string.lstrip("我")) #去掉左边界字符
是谁谁是我
>>> print(string.rstrip("我是")) #去掉右边界字符
我是谁谁

>>> name = '\n Harry Potter\n '
>>>> name2 = name.strip() #默认去掉空格和换行符
>>> name2
'Harry Potter'
>>> name2 = name.strip('\nHr') # 只会去掉'\n'
>>> name2
' Harry Potter\n '
>>> name2 = name.strip('\n Hr') #去掉'\n'、' '、'H'、'r'
>>> name2
'arry Potte'

⑦ format(),格式化字符串,使用{}作为占位符

>>> print("{} * {} = {}".format(a,b,a*b))
2 * 3 = 6

⑧ f,格式化字符串的另一种实现,python3.6后支持,作用和format一致,用法如下

>>> print(f"""{a} * {b} = {a*b}""")
2 * 3 = 6

@[TOC]列表list

  • 用于存储多个数据的一种数据类型
  • 格式:[value1,value2,…]
  • 列表当中的元素可以是Python任意数据类型
  • 可以无限嵌套
  • array只能是同一种数据类型

1)索引index,获取列表中的一个元素,逻辑和字符串索引一致

>>> list1=["a","b",[1,2,"33a"]]
>>> list1[0]
'a'
>>> list1[2]
[1, 2, '33a']
>>> list1[2][2] #列表嵌套取值
'33a'
>>> list1[3] #超出索引范围
Traceback (most recent call last):
  File "<pyshell#96>", line 1, in <module>
    list1[3]
IndexError: list index out of range

2)切片slice,获取列表某些元素,逻辑和字符串切片一致

>>> list1=["a","b",[1,2,"33a"],{}]
>>> list1[1:3]
['b', [1, 2, '33a']]
>>> list1[-1]
{}

3)列表添加,注意列表是可变数据类型,修改列表直接改变列表自身
① append(),在列表最后添加元素

>>> list_test = ['你好','你是谁','你来自哪里']
>>> list_test.append(("我来自中国"))
>>> list_test
['你好', '你是谁', '你来自哪里', '我来自中国']

② insert(index,data),在指定索引位置添加元素

>>> list_test = ['你好','你是谁','你来自哪里']
>>> list_test.insert(1,"我来自中国") #添加到索引1位置,其他元素依次后移
>>> list_test
['你好', '我来自中国', '你是谁', '你来自哪里']

③ extend([]),参数是个列表,用于添加多个元素(也可以理解为列表合并),注意传参为列表和append的区别,append是将列表作为一个元素添加

>>> list_a = ["a","b","c"]
>>> list_b = [1,2,3]
>>> list_a.extend(list_b) #list_b的元素依次添加
>>> list_a
['a', 'b', 'c', 1, 2, 3]
>>> list_a.append(list_b)
>>> list_a
['a', 'b', 'c', 1, 2, 3, [1, 2, 3]] #list_b的元素作为一个整体添加

4)列表删除
① remove(),在列表中删除指定的一个元素,如有多个相同元素,删除出现的第一个。参数是元素值

>>> list_test = ['你好','你是谁','你来自哪里']
>>> list_test.remove("你是谁")
>>> list_test
['你好', '你来自哪里']
>>> list.remove("好的") #删除不存在的元素将报错
Traceback (most recent call last):
  File "<pyshell#116>", line 1, in <module>
    list.remove("好的")
TypeError: descriptor 'remove' for 'list' objects doesn't apply to a 'str' object

② del,一般不建议使用,会改变内存

>>> list_test = ['你好','你是谁','你来自哪里']
>>> del list_test[0]
>>> list_test
['你是谁', '你来自哪里']
>>> list_test = ['你好','你是谁','你来自哪里']
>>> del list_test[0:2] #删除列表索引为0,1的元素
>>> list_test
['你来自哪里']

③ pop(),删除列表内指定索引的一个元素,不指定则默认删除最后一个

>>> list_test = ['你好','你是谁','你来自哪里']
>>> list_test.pop(0)
'你好'
>>> list_test
['你是谁', '你来自哪里']
>>> list_test = ['你好','你是谁','你来自哪里']
>>> list_test.pop() #不传参默认删最后一个
'你来自哪里'
>>> list_test
['你好', '你是谁']

5)列表修改
① 单个元素修改

>>> list_test = [1,2,3,4]
>>> list_test[0] = 100
>>> list_test
[100, 2, 3, 4]

② 批量修改,可以分开写,也可以使用切片方式

>>> list_test = [1,2,3,4]
>>> list_test[0],list_test[1] = 100,200
>>> list_test
[100, 200, 3, 4]
>>> list_test[2:] = 300,400  #切片
>>> list_test
[100, 200, 300, 400]

6)列表其它一些常用方法
① count(),返回某个元素出现的次数

>>> list_test = [1,2,3,3,3,1,100]
>>> print(list_test.count(1))

② index(),返回某个元素第一次出现的索引

>>> list_test = [1,2,3,3,3,1,100]
>>> print(list_test.index(1))
0

③ sort(),将可排序的列表序列从小到大排序,如果是字符,根据ASCII编码排序,不能比较的列表会报错,如果要实现从大到小排序,则指定reverse=True

>>> list_test = [776,2,3,5,3,1,100]
>>> list_test.sort() #将列表元素从小到大排序
>>> print(list_test)
[1, 2, 3, 3, 5, 100, 776]
>>> list_test = [776,"2",3,5,3,1,100]
>>> list_test.sort() #列表元素有字符串和数值类型,不能比较,排序将报错TypeError
Traceback (most recent call last):
  File "<pyshell#151>", line 1, in <module>
    list_test.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
[100, 1, 3, 5, 3, '2', 776]
>>> list_test = [776,2,3,5,3,1,100]
>>> list_test.sort(reverse=True) #从大到小排序,或者叫逆序排序
>>> list_test
[776, 100, 5, 3, 3, 2, 1]

④ reverse(),将列表逆序,物理位置(索引)

>>> list_test = [776,"2",3,5,3,1,100]
>>> list_test.reverse()
>>> list_test
[100, 1, 3, 5, 3, '2', 776]

⑤ clear(),清除列表的所有元素,结果返回一个空列表

>>> list_test = [776,2,3,5,3,1,100]
>>> list_test.clear()
>>> list_test
[]

@[TOC]字典dict

  • 格式:键值对形式 {key1:value1,key2:value2,…}
  • key值唯一,且列表不能作为key
  • 可变的数据类型,无序
  • 字典没有切片或者索引,通过dict[key]去获取字典元素值

1)字典查询
① dict[‘key’],返回key对应的value值

>>> mydict={"喜欢的蔬菜":"萝卜","讨厌的蔬菜":"秋葵"}
>>> mydict["讨厌的蔬菜"]
'秋葵'

② dict.items(),返回键和值,较常使用,常见用法如下

>>> mydict = {'喜欢的蔬菜': '茄子', '讨厌的蔬菜': '秋葵', '喜欢的水果': '山竹'}

>>> for key,value in mydict.items():
	print(key,value)

	
喜欢的蔬菜 茄子
讨厌的蔬菜 秋葵
喜欢的水果 山竹

③ dict.keys(),返回字典所有键

>>> mydict = {'喜欢的蔬菜': '茄子', '讨厌的蔬菜': '秋葵', '喜欢的水果': '山竹'}
>>> mydict.keys()
dict_keys(['喜欢的蔬菜', '讨厌的蔬菜', '喜欢的水果'])

④ dict.values(),返回字典所有值

>>> mydict = {'喜欢的蔬菜': '茄子', '讨厌的蔬菜': '秋葵', '喜欢的水果': '山竹'}
>>> mydict.values()
dict_values(['茄子', '秋葵', '山竹'])

2)字典修改

>>> mydict={"喜欢的蔬菜":"萝卜","讨厌的蔬菜":"秋葵"}
>>> mydict["喜欢的蔬菜"] = "茄子"
>>> mydict
{'喜欢的蔬菜': '茄子', '讨厌的蔬菜': '秋葵'}

3)字典增加,和字典修改形式一样,key有则该,无则增。

>>> mydict={"喜欢的蔬菜":"萝卜","讨厌的蔬菜":"秋葵"}
>>> mydict["喜欢的水果"] = "山竹"
>>> mydict
{'喜欢的蔬菜': '茄子', '讨厌的蔬菜': '秋葵', '喜欢的水果': '山竹'}

4)字典删除
① del

>>> mydict = {'喜欢的蔬菜': '茄子', '讨厌的蔬菜': '秋葵', '喜欢的水果': '山竹'}
>>> del mydict["讨厌的蔬菜"]
>>> mydict
{'喜欢的蔬菜': '茄子', '喜欢的水果': '山竹'}

② clear(),清除所有元素

>>> mydict.clear()
>>> mydict
{}

③ pop(key),参数不能为空,返回删除的键值
popitem(),返回并删除字典中最后一对键值对

>>> mydict = {'喜欢的蔬菜': '茄子', '讨厌的蔬菜': '秋葵', '喜欢的水果': '山竹'}
>>> mydict.pop() # 参数不能为空
Traceback (most recent call last):
  File "<pyshell#174>", line 1, in <module>
    mydict.pop()
TypeError: pop expected at least 1 argument, got 0
>>> mydict.pop("喜欢的蔬菜")
'茄子'
>>> mydict
{'讨厌的蔬菜': '秋葵', '喜欢的水果': '山竹'}
>>> mydict.popitem()
('喜欢的水果', '山竹')
>>> mydict
{'讨厌的蔬菜': '秋葵'}

@[TOC]元组tuple

  • 格式: (value1,value2,…)
  • 和列表非常相似,内部支持数值、字符串、列表、元组(嵌套)
  • 元组不可变,只能获取(查)
  • 当元组只有一个元素时,元素后面加逗号 (1,)
  • 下面简单举例常见方法
>>> mytuple=(1,)
>>> mytuple
(1,)
>>> mytuple=(1,1,2,3,[],{},())
>>> mytuple.count(1) #获取元素1出现的次数
2
>>> mytuple[2] #获取索引为2的元素
2
>>> mytuple.index({}) #获取元素{}的索引
5

@[TOC]集合set

  • 格式:{value1,value2,…}
  • 集合总元素不能重复
  • 集合中的元素必须是不可变的数据类型,如列表、字典、集合都不可以,即集合不可以嵌套
  • 可变的数据类型,无序
  • 常用方法,与列表类似,不一一举例

TODO:使用场景
① 对列表元素去重
② set()函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等

>>> mylist = [900,1,1,5,5,0,3,4,5,0,999,100,999]
>>> set(mylist) #转为集合,将去除重复元素
{0, 1, 3, 900, 5, 4, 999, 100}
>>> list(set(mylist)) #集合再转为列表,实现列表去重
[0, 1, 3, 900, 5, 4, 999, 100]

@[TOC]数据类型总结

1)通过type()获得任意对象的数据类型

>>> type({"price":1})
<class 'dict'>

2)在可以转换的前提下,通过int(),float(),list()等方法实现数据类型转换。

>>> a = "12345"
>>> type(a)
<class 'str'>
>>> a = int(a)
>>> a
12345
>>> type(a)
<class 'int'>

3)TODO:数据类型是否可变。区分标准,定义一个集合,可以作为set元素的是不可变数据类型,不能放到set中的是可变数据类型。
① int,float,bool,str,tuple为不可变数据类型;
② list,dict,set为可变数据类型

>>> myset = {1,2.333,True,"love and peace",(1,2)} #int,float,bool,str,tuple不可变,可作为set的元素
>>> myset
{1, 2.333, (1, 2), 'love and peace'}
>>> myset = {[1,2]} #列表可变
Traceback (most recent call last):
  File "<pyshell#212>", line 1, in <module>
    myset = {[1,2]}
TypeError: unhashable type: 'list'
>>> myset = {{"name":"Tom"}} #字典可变
Traceback (most recent call last):
  File "<pyshell#217>", line 1, in <module>
    myset = {{"name":"Tom"}}
TypeError: unhashable type: 'dict'
>>> myset = {{1,2}} #集合可变
Traceback (most recent call last):
  File "<pyshell#218>", line 1, in <module>
    myset = {{1,2}}
TypeError: unhashable type: 'set'

4)序列数据类型list,dict,tuple,set,其中list和tuple有序,dict和set无序

5)关于各个数据类型的bool值:
① 字符串,非空为True,空为False;
② 数值,非0为True,0为False;
③ 除空列表外,任何列表、元组、集合和字典均为 True。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值