ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python学习笔记(基础入门篇)

2021-04-22 17:31:25  阅读:155  来源: 互联网

标签:chuid chd name Python list 笔记 dic 入门篇 print


安装python编译器
1.安装依赖包
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel
2.下载python解释器
wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tgz
3.解压安装
tar -zxf Python-3.7.3.tgz
cd Python-3.7.3/
./configure --prefix=/usr/local/python3
make && make install
4.建立软连接
ln -s /usr/local/python3/bin/python3.7 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3.7 /usr/bin/pip3
5.测试python环境
[root@python ~]# python3
Python 3.7.3 (default, Dec 23 2020, 16:50:35) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('hello world!')
hello world!
>>> quit()
[root@python ~]#


变量
可以理解为:变化的量
变量的组成
变量名:变量名用来引用变量值,定义变量值需要通过变量名。
赋值符号:赋值。
变量值:存放数据,用来记录现实世界中的某种状态。

例子:
>>> name = ('chd')
>>> age = 27
>>> height = 170
>>> 
>>> print(age)
27
>>> print(height)
170
>>>
变量命名的三个规范
1.变量名由字母(Unicode字符,不包括特殊字符)、数字和下划线构成,数字不能开头。
2.区分大小写(大写的A和小写的a是两个不同的变量)
3.不要跟关键字(有特殊含义的单词)和系统保留字(函数、模块等的名字)

变量名的两种风格
1.驼峰体
>>> MyName = 'chd'
>>> MyAge = 27
>>> 
>>> print(MyAge)
27
2.下划线 <推荐>
>>> my_name = 'chuid'
>>> my_age = 26
>>> 
>>> print(my_age)
26


数据类型
1.整型(int)
作用:表示人的年龄、各种号码、级别
应用:加减乘除、逻辑判断(大于、小于)

例子:
>>> name = 'chd'
>>> age = 27
>>> 
>>> print(id(age))
9463584
>>> print(type(age))
<class 'int'>
>>> print(age)
27

2.浮点型(float)
作用:表示身高、体重、薪资
应用:加减乘除、逻辑判断(大于、小于)

例子:
>>> BodyWeight = 128.5
>>>
>>> print(id(BodyWeight))
140018111439160
>>> print(type(BodyWeight))
<class 'float'>
>>> print(BodyWeight)
128.5

3.列表(list)
作用:存放多个值,如兴趣爱好、书籍
定义:在[]内用逗号隔开任意类型的值

例子:
>>> hobby = 'travel'
>>> hobby_list = ['read','shopping']
>>> 
>>> print(id(hobby_list))
139940700505544
>>> print(type(hobby_list))
<class 'list'>
>>> print(hobby_list)
['read', 'shopping']

例子:
介绍索引取值的方法,索引序号从0开始
>>> colour_list = ['purple','blue','red']
# 索引序号            0       1      2
>>> print(colour_list[1])
# 取出第二个颜色
blue
>>> 
>>> Information = ['travel','read',['chd',27,'hubei']]
# 取出chd的年龄
>>> print(Information[2][1])
27

4.字典(dict)
作用:用来存取多个值,按照key:value的方式存值,取的时候可以通过key而非索引去取值,key对value具有描述性的作用。存放很多种类数据并且数据较多的时候可以使用字典。
定义:在{}内用逗号分隔开多个元素,每一个元素都是key:value的格式,其中value是任意格式的数据类型,key由于具有描述性的作用,所以key通常是字符串类型。

例子:
>>> user_info = {'name':'chd','gender':'male','age':27,'hobby':['travel','read','shopping']}
>>> 
>>> print(id(user_info))
140332757454712
>>> print(type(user_info))
<class 'dict'>
>>> print(user_info)
{'name': 'chd', 'gender': 'male', 'age': 27, 'hobby': ['travel', 'read', 'shopping']}

例子:
字典取值方式不再依赖于索引,而是依赖于key,通过[key]即可获取key对应的value值
(1).字典套列表
>>> user_info = {'name':'chd','gender':'male','age':27,'hobby':['travel','read','shopping']}
>>> 
>>> print(user_info['name'])
chd
>>> print(user_info['hobby'][1])
read
(2).字典套字典
>>> user_info = {'name':'chd','gender':'male','age':27,
'hobby':{'movement':'travel','learn':'read','life':'shopping'}}
>>> 
>>> print(user_info['name'])
chd
>>> print(user_info['hobby']['learn'])
read


Python与用户交互
为什么交互?
计算机的发明是为了奴役计算机,解放劳动力。假设我们要在银行的ATM机上转账和取款,那么这个ATM会要求我们输入银行账号和密码,还需要我们输入取款金额,这就可以理解为一种交互。

例子:
# 使用input()的方法接收值
>>> name = input("please enter password: ")
please enter password: chd
>>> pwd = input("please enter password: ")
please enter password: 123456
>>> print(type(name))
<class 'str'>
>>> print(type(pwd))
<class 'str'>


格式化输出的三种方式
1.占位符
%s : 针对所有数据类型
%d : 针对数字类型

例子:
# 不使用占位符的方法
>>> age = 27
>>> print('my name is chd, my age is'+str(age))
my name is chd, my age is27
>>> print('my name is chd, my age is',age)
my name is chd, my age is 27

例子:
# 使用占位符的方法
>>> age = 27
>>> print('my name is chd, my age is %d' % age)
my name is chd, my age is 27
>>> 
>>> name = 'chd'
>>> print('my name is %s, my age is %d' % (name,age))
my name is chd, my age is 27
2.format格式化(不推荐使用)

例子:
>>> name = 'chd'
>>> age = 27
>>> 
>>> print('hey {}. You are {}.'.format(name,age))
hey chd. You are 27.
>>> print('hey {}. You are {} years old.'.format(name,age))
hey chd. You are 27 years old.

3.f-String格式化(推荐使用)

例子:
>>> name = 'chd'
>>> age = 27
>>> 
>>> print(f'hey,{name}. You are {age} years old.')
hey,chd. You are 27 years old.
>>> print(f'hey,{name}. You are {age}.')
hey,chd. You are 27.
# 也可以使用大写的F
>>> print(F'hey,{name}. You are {age}.')
hey,chd. You are 27.

例子:
>>> age = 26
>>> print(f'{age*2}')
52


基本运算符
1.算数运算符
以下假设变量a为10,变量b为20
 
例子:
# 加法
>>> print(1 + 2)
3
>>> 
>>> x = 10
>>> y = 20
>>> addition = x + y
>>> print(addition)
30
# 除法
>>> print(10 / 3)
3.3333333333333335
# 地板除(只取整数部分)
>>> print(10 // 3)
3
# 取余
>>> print(10 % 3)
1
# 幂
>>> print(10**3)
1000

2.比较运算符
 
例子:
>>> chd = '123'
>>> print(chd != '123')
False
>>> print(chd == '123')
True

>>> a = 10
>>> b = 20
>>> a > b
False
>>> a < b
True

3.赋值运算符
 

例子:
>>> a = 15
>>> b = 30
>>> c = a + b
>>> c += a
>>> print(c)
60
>>> c /= a
>>> print(c)
4.0
>>> c *= a
>>> print(c)
60.0
>>> c /= a
>>> print(c)
4.0
>>> c *= b
>>> print(c)
120.0
>>> c //= a
>>> print(c)
8.0

4.逻辑运算符
以下假设变量a为10,变量b为20
 

例子:
# 从左到右找到逻辑运算符,左边成立,再去找逻辑运算符的右边
>>> print(3 > 5 and 1 > 3 or 6 > 5)
True

5.身份运算符
身份运算符用于比较两个对象的存储单元
 
例子:
>>> x = 258
>>> y = x
>>> z = 258
>>> print(f'x is y:{x is y}')
x is y:True
>>> print(f'x == y:{x == y}')
x == y:True
>>> print(f'x is z:{x is z}')
x is z:False
>>> print(f'x == z:{x == z}')
x == z:True
>>>
>>> print(id(x))
140029981893776
>>> print(id(z))
140029981893680

6.位运算符
按位运算符是把数字看作二进制进行计算的。Python中的按位运算法则如下:
下表中变量a为60,b为13,二进制格式如下:
 
例子:
a = 0011 1100
b = 0000 1101
------------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

例子:
>>> a = 60    # 60 = 0011 1100
>>> b = 13    # 13 = 0000 1101
>>> c = 0
>>> c = a & b
>>> print(c)
12
>>> c = a | b
>>> print(c)
61
>>> c = a ^ b
>>> print(c)
49
>>> c = ~a
>>> print(c)
-61
>>> c = a << 2
>>> print(c)
240
>>> c = a >> 2
>>> print(c)
15

7.成员运算符
除了以上的一些运算符之外,Python还支持成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组。
 
例子:
a = 5
b = 10
list = [1, 2, 3, 4, 5]
if (a in list):
    print('a in list.')
else:
    print('a not in list.')
>>> a in list.

a = 5
b = 10
list = [1, 2, 3, 4, 5]

if (b in list):
    print('b in list.')
else:
    print('b not in list.')
>>> b not in list.
8.Python运算符优先级
Python运算符的优先级相当于数学中的先算乘除再算加减
 

例子:
a = 20
b = 10
c = 15
d = 5
e = 0

e = (a + b) * c / d     #(30 * 15)/ 5
print ("('a + b') * c / d 运算结果为:", e)
>>> ('a + b') * c / d 运算结果为: 90.0


Python变量内存管理
1.变量存哪了?
例子1:当我们定义一个变量:x = 52 , 计算机会把这个变量值52存放到电脑内存中。
理解记忆:
把学校看成电脑内存,教室看成存放变量值52,班级名看成变量名x,x指向52
 

2.Python垃圾回收机制
例子2:当变量x = 52时,如果再加一个 x = 56,电脑内存会另外存储变量值56,此时变量名x会解除与52的连接并与56连接,由于52没有了变量名,所以就会被回收,并将52的内存占用释放掉。

2.1引用计数
从例2的解释中可以知道,只要变量值绑定着变量名就不会被清理,如果变量值没有绑定变量名就会被垃圾回收机制自动清理,这里的变量名有一个专业词汇叫引用计数
例子:
x = 52   # 52的引用计数为1(x = 52)
y = x    # 52的引用计数为2(y = x = 52)
x = 56   # 52的引用计数为1, 56的引用计数为1(x = 56 ,y = 52)
del y    # 52的引用计数为0,触发垃圾回收机制清理52的内存占用
print(id(x))
>>> 8791517391216

3.小整数池
理解了引用计数后需要注意的是:Python实现int(整数)的时候有个小整数池。为了避免因创建相同的值而重复申请空间所带来的效率问题,Python解释器会在启动时创建出小整数池,范围是[-5,256],该范围内的小整数对象是全局解释器范围内被重复使用,永远不会被垃圾回收机制回收。
在pycharm中运行python程序时,pycharm出于对性能的考虑,会扩大小整数池的范围,其他的字符串等不可变类型也都包含在内以采用相同的方式处理了。


变量的三个特征
对于每个变量,python都提供了三个方法获取变量的三个特征:
(1)打印python的内置功能id()
内存地址不一样则id()后打印的结果也不一样,因为每一个变量值都有其唯一的内存地址,而id是用来反映变量值在内存中的位置,内存地址不太则id不同。
例子:
x = 52
print(id(x))
print(type(x))
print(x)
>>> 8791510051056
>>> <class 'int'>
>>> 52
(2)判断变量值是否相等
例子:
x = 'chd'
y = 'chuid'
print(x == y)
>>> False
(3)判断变量id是否相等
例子1:
x = 52
y = x
z = 52
print(x == y)   # True
print(x is y)   # True
print(x is z)   # True ,整数池的原因
>>> True
>>> True
>>> True
例子2:
x = 522
y = 522
print(x is y)
>>> False
综上所述:id相等的变量,值一定相等,指向的是同一个内存地址;值相等的变量,id不一定相等。


条件控制之if判断
Python条件语句是通过一条或多条语句的执行结果(True/False)来决定执行的代码块。
 
1.if判断语句
if表示:if成立代码会干什么。
例子:
name = 'chd'
age = 20

if name == "chd" and age > 16 and age < 25 :
    print('is OK')
print('end...')
>>> is OK
>>> end...

2.if...else语句
if...else表示:if成立代码会干什么,else不成立会干什么。
例子:
name = 'chd'
age = 20

if name == "chd" and age > 16 and age < 18 :
    print('hi,chd')
else:
    print('is NO')
print('end...')
>>> is NO
>>> end...


3.if...elif...else语句 
[elif是else if的缩写]
if...elif...else表示:if条件成立干什么,elif条件1成立干什么,elif条件2成立干什么,elif否则干什么。
例子:
name = 'chd'
age = 26

if age >= 27:
    print('too big')
elif age >= 25:
    print('almost')
else:
    print('too small')
>>> almost
if语句执行有个特点:它是从上往下判断,如果在某个判断上是True ,把该判断对应的语句执行后,就忽略掉剩下的elif和else
例子:
# 判断成绩
name = 'chd'
test = input('grades: ')
grades = int(test)
if grades >= 90:
    print('Excellent')
elif grades >= 80 and grades < 90:
    print('good')
elif grades >= 70 and grades < 80:
    print('general')
else:
    print('difference')
>>> grades: 86
>>> good

4.if嵌套
在嵌套if语句中,可以把if...elif...else结构放在另一个if...elif...else结构中
例子:
nu = int(input(‘输入一个数字:’))
if nu % 5 == 0:
    if nu % 7 == 0:
        print (‘你输入的数字可以整除 5 和 7’)
    else:
        print (‘你输入的数字可以整除 5,但不能整除 7’)
else:
    if nu % 7 == 0:
        print (‘你输入的数字可以整除 7,但不能整除 5’)
    else:
        print  (‘你输入的数字不能整除 5 和 7’)
>>> 输入一个数字:35
>>> 你输入的数字可以整除 5 和 7


知识串讲 input
在用户交互中用过input()读取用户的输入,需要注意的是input()返回的数据类型是字符串(str),str不能和整数比较,必须先把str转换成整数(int)。否则会程序会报错!
例1:
s = input('birth: ')
birth = int(s)
if birth < 2000:
    print('after 00')
else:
    print('before 00')
>>> birth: 1993
>>> after 00

float()函数 [浮点型]
作用:float()函数用于将整数和字符串转换成浮点数。

eval()函数
作用:eval()函数用来执行一个字符串表达式,并返回表达式的值。

下面例2中因为变量名height和weight在单位转换后有可能产生小数,所以这里需要使用float()和eval()函数
方法1:用float()函数
方法2:用eval()函数

例2:
# 根据BMI公式(体重除以身高的平方),计算BMI指数
name = 'chd'
height = float(input('请输入身高(m): '))   # 这里可以将float()函数替换成eval()函数
weight = float(input('请输入体重(kg): '))  # 这里可以将float()函数替换成eval()函数
bmi = weight/(height**2)
print('你的BMI指数为: ',bmi)
if bmi < 18.5:
    print('你的身体状态:too light')
elif bmi >= 18.5 and bmi < 25:
    print('你的身体状态:normal')
elif bmi >= 25 and bmi < 28:
    print('too heavy')
elif bmi >= 28 and bmi < 32:
    print('你的身体状态:obesity')
else:
    print('你的身体状态:severe obesity')
>>> 请输入身高(m): 1.7
>>> 请输入体重(kg): 65
>>> 你的BMI指数为:  22.49134948096886
>>> 你的身体状态:normal



条件控制之while循环
1.循环就是一个重复的过程,while循环又称为条件循环。
 

例子:用户登录程序
user = 'chd'
pwd = '123'
in_user = input('name: ')
in_pwd = input('pwd: ')
if in_user == user and in_pwd == pwd:
    print('登录成功')
else:
    print('登陆失败')
>>> name: chd
>>> pwd: 123
>>> 登录成功

2.while循环
例子:
while True:
    user = 'chd'
    pwd = '123'
    in_user = input('name: ')
    in_pwd = input('pwd: ')
    if in_user == user and in_pwd == pwd:
        print('登录成功')
    else:
        print('登陆失败')
>>> name: chd
>>> pwd: 123
>>> 登录成功
>>> name:
虽然while循环实现了例1的功能,但是用户面输对了,他也会继续输入。

3.While + break
作用:Break的意思是终止掉当前层的循环,执行其他代码。
例:1:
while True:
    user = 'chd'
    pwd = '123'
    in_user = input('name: ')
    in_pwd = input('pwd: ')
    if in_user == user and in_pwd == pwd:
        print('登录成功')
        break
    else:
        print('登陆失败')
>>> name: chd
>>> pwd: 123
>>> 登录成功

例子2:
while True:
     passwd = input('请输入密码:')
     if(passwd == '123'):
         print('登陆成功')
         break
         print('您的余额还有0')
     else:
         print('登陆失败')
>>> 请输入密码:1234
>>> 登陆失败
>>> 请输入密码:123
>>> 登陆成功

例子:用户登陆程序,三次机会
i = 0
while i < 3:
    in_user = input('name: ')
    in_pwd = input('pwd: ')
    if in_user == 'chd' and in_pwd == '123':
        print('登录成功')
        break
    else:
       print('用户名和密码错误')
       print('你还有%d次机会' %(2-1))
       i += 1
else:
      print('登陆超过3次,请等50分钟后再次登陆')
>>> name: chd
>>> pwd: 123
>>> 登录成功

4.while + continue
作用:continue的意思是终止本次循环,直接进入下一次循环。
例子1:
n = 1
while n < 3:
    print(n)
    n += 1
>>> 1
>>> 2

例子2:
n = 1
while n < 12:
    if n == 10:
        n += 1    # 这一行被注释会进入死循环
        continue
    print(n)
    n += 1        # 这一行被注释会进入死循环
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5
>>> 6
>>> 7
>>> 8
>>> 9
>>> 11


例子3:
n = 5
while n > 0:
    n -= 1
    if n == 2:
        continue
    print(n)
print('循环结束.')
>>> 4
>>> 3
>>> 1
>>> 0
>>> 循环结束.

continue不能是加在循环体的最后一步执行的代码(不是最后一行),因为代码加上去毫无意义。


5.while循环的嵌套
ATM程序密码输入成功后需要进行一系列的操作,比如存取款、转账。并在执行功能结束后提示继续执行,输入q会退出输出功能的while循环并退出ATM程序。

例子:退出双层循环的while循环嵌套
while True:
    user = 'chd'
    pwd = '123'
    in_user = input('username: ')
    in_pwd = input('password: ')
    if in_user == user and in_pwd == pwd:
        print('登陆成功')
    
	    while True:
            chuid = input('请输入: ')
            if chuid == 'q':
                break
            print(f'{chuid} 执行')
        break                    # 去掉这里的break就是内层循环的while循环嵌套
    else:
        print('登陆失败')
print('退出while循环')
>>> username: chd
>>> password: 123
>>> 登陆成功
>>> 请输入: 1
>>> 1 执行
>>> 请输入: q
>>> 退出while循环

6.tag控制循环退出
tag = True
while tag:
    passwd = input('请输入密码:')
    if(passwd == '123'):
        print('登陆成功')
        tag = False
    else:
        print('登录失败,请重新登录')
print('您的余额为0')
>>> 请输入密码:123456
>>> 登录失败,请重新登录
>>> 请输入密码:123
>>> 登陆成功
>>> 您的余额为0


7.while与else连用
在while中也可以使用else,要想让else的代码运行,必须要while结束循环以后,并且循环不是因为break中断结束才可以。

例子1:
n = 1
while n < 5:
    print(n)
    n += 1
else:
    print('ok')
>>> 1
>>> 2
>>> 3
>>> 4
>>> ok

例子2:
从0开始输出一个整数,在整数6的位置添加了break(限制到整数小于6),大于6就会被break退出。
count = 0
b = int(input('请输入1-5:'))
while count <= b:
    print(count)
    if count == 6:
        break
    count += 1
else:
    print('正常退出')
>>> 请输入1-5:5        # 输入小于6的任意数,else都会同步输出
>>> 0
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5
>>> 正常退出
------------------------------------------------------------------------------
>>> 请输入1-5:8       # 如果大于整数5,就不会运行else语句了 
>>> 0
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5
>>> 6


案例用法:将上面的ATM取款机代码进行优化(取款机代码限制输错次数3次)
count = 0        # 计次数
while count < 3:
    username = input('请输入账户:')
    password = input('请输入密码:')
    if username == 'chd' and password == '123':
        print('登陆成功!')
        break
    else:
        count += 1
        print('密码错误{}次'.format(count))
else:
    print('密码错误三次,卡已被冻结.')
>>> 请输入账户:chd
>>> 请输入密码:123
>>> 登陆成功!
----------------------------------------------------------
>>> 请输入账户:chd
>>> 请输入密码:1234
>>> 密码错误1次
>>> 请输入账户:chd
>>> 请输入密码:12345
>>> 密码错误2次
>>> 请输入账户:chd
>>> 请输入密码:123456
>>> 密码错误3次
>>> 密码错误三次,卡已被冻结.


条件控制之for循环
for循环,又被称为迭代循环(取值循环),是python提供的第二种循环机制,从理论上for循环能做的事情,while循环都能做,for循环在循环取值上面比while更加简便。
for x in ['chd','chuid','chen']:
    print(x)
>>> chd
>>> chuid
>>> chen
for循环会将可迭代对象中的值一个个的取出来,直到整个可迭代对象的值被取干净为止
for循环的次数取决于可迭代对象内部值的个数
for循环取字典,默认取出来的是字典的key,取value可以通过dic[key]的方式
dic = {'name':'chd','age':'27','weghit':'130','height':'170'}
for x in dic:
    print(x,':',dic[x])
>>> name : chd
>>> age : 27
>>> weghit : 130
>>> height : 170


for循环控制循环次数
1.range()
函数range()的功能是生成从0开始的数组,括号里是多少,就生成序号到多少的列表
for i in range(3):
    print(i)
>>> 0
>>> 1
>>> 2

2.for + continue
for循环和while循环与continue连用效果相同,其作用是结束掉本次循环,直接进入下一次
for i in range(5):
    if i == 3:
        continue   # 终止本次循环i == 3,直接进入下一次循环,所以输出的结果里面没有3
    print(i)
>>> 0
>>> 1
>>> 2
>>> 4

3.for + break
for循环终止本次循环
username = ['chd','chuid','chen']
for name in username:
    if name == 'chuid':
        break
    print(name)
>>> chd
-------------------------------------------------------
username = ['chd','chuid','chen']
for name in username:
    if name == 'chuid':
        continue
    print(name)
>>> chd
>>> chen

4.for循环实现loading
print('loading',end=' ')
for i in range(6):
    print('.',end='')
    time.sleep(0.5)
>>> loading ......

5.for循环嵌套(九九乘法表)
for a in range(1,10):
    for b in range(1,a+1):
        print('{}*{}={}'.format(a,b,a*b),end=' ')   # end=' '参数内要有空格,否则输出的结果都连在一起了
    print('')
>>> 1*1=1 
>>> 2*1=2 2*2=4 
>>> 3*1=3 3*2=6 3*3=9 
>>> 4*1=4 4*2=8 4*3=12 4*4=16 
>>> 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 
>>> 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 
>>> 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 
>>> 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 
>>> 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

6.for + else
for循环没有break的时候触发else内代码
username = ['chd','chuid','chen']
for name in username:
    print(name)
else:
    print('for循环没有中断')
>>> chd
>>> chuid
>>> chen
>>> for循环没有中断
-----------------------------------------------------------
username = ['chd','chuid','chen']
for name in username:
    if name == 'chen':
       break
    print(name)
else:
    print('for循环没有中断')
>>> chd
>>> chuid

7.pass语句
Pass是空语句(不做任何事情,一般用做占位语句),是为了保持程序结构的完整性。
for letter in 'Chuid':
    if letter == 'u':
        pass
        print('执行 pass 块')
    print('当前字母 :', letter)
print('结束.')
>>> 当前字母 : C
>>> 当前字母 : h
>>> 执行 pass 块
>>> 当前字母 : u
>>> 当前字母 : i
>>> 当前字母 : d
>>> 结束.


本章小结综合实战  <猜年龄游戏>
age = 26  # 答案
count = 0  # 游戏次数控制
prize_dict = {0:'蜡笔小新',1:'手表',2:'水杯',3:'<python笔记>'}

# 与用户交互(核心)
while count < 3:
    inp_age = input('请输入你的年龄:')  # 与用户交互

# 判断用户是否骚扰(判断用户输入的是否为数字)
    if not inp_age.isdigit():
        print('输入错误!')
        continue
    inp_age_int = int(inp_age)

# 判断年龄(核心)
    if inp_age_int == age:
        print('猜对了')
        print(prize_dict)

# 获取两次奖品  与用户交互获得奖品
        for i in range(2):
            prize_choice = input('请输入你想要的奖品,如果不想要,则输入"n"退出!')

# 判断是否需要奖品
            if prize_choice != 'n':
                print(f'恭喜你获得奖品:{prize_dict[int(prize_choice)]}')
            else:
                break
        break
    elif inp_age_int < age:
        print('猜小了')
    else:
        print('猜大了')

    count += 1  # 成功玩一次游戏

    if count != 3:
        continue

    again_choice = input('是否继续游戏,继续请输入"Y",否则任意键直接退出.')   # 交互是否再一次

    # 判断是否继续
    if again_choice == 'Y':
        count = 0
>>> 请输入你的年龄:26
>>> 猜对了
>>> {0: '蜡笔小新', 1: '手表', 2: '水杯', 3: '<python笔记>'}
>>> 请输入你想要的奖品,如果不想要,则输入"n"退出!n

数字类型内置方法(int)
整型和浮点型统称为数字类型
1.整型内置方法(int)
作用:年龄、号码、等级
定义:可以使用int()方法将纯数字的字符串转为十进制的整型
age = 27
print(type(age))
>>> <class 'int'>

可变和不可变
id不变,值可变,即在原值的基础上修改,则为可变数据类型;
值变;id也变,即重新申请一个空间放入新值,则为不可变数据类型。
age = 27
print(type(age))
print(id(age))
age = 26
print(f'first:{id(age)}')
age = 27
print(f'second:{id(age)}')
>>> <class 'int'>
>>> 8791428982224
>>> first:8791428982192
>>> second:8791428982224

2.浮点型内置方法(float)
作用:薪资、身高、体重
定义:可以使用float()方法将纯数字的字符串转为浮点型数字
age = 27.1
print(type(age))
print(id(age))
>>> <class 'float'>
>>> 3584480
age = 27
print(type(age))
print(id(age))
>>> <class 'int'>
>>> 8791428982224
-------------------------------------------------
i = float('27')
print(i)
print(type(i))
print(id(i))
>>> 27.0
>>> <class 'float'>
>>> 1487328


salary = 26.1
print(f'first:{id(salary)}')
salary = 27.1
print(f'second:{id(salary)}')
>>> first:5616096
>>> second:5616072

字符串类型内置方法(str)
作用:描述性质的东西,如人的名字、单个爱好、地址、国家等
定义:使用‘’“”‘“”’包含的一串字符
name = "chd"
print(type(name))
i = str(1.5)
print(f'i:{i}, type:{type(i)}')
>>> <class 'str'>
>>> i:1.5, type:<class 'str'>

1.按索引取值
# str索引取值
abc = 'hello chd'
#      012345678   # 索引序号

print(f'索引号为8:{abc[8]}')
print(f'索引号为3:{abc[3]}')
>>> 索引号为8:d
>>> 索引号为3:l

2.切片
# 索引切片
msn = 'hello chd'
#      012345678    # 索引序号
print(f'切片2-最后:{msn[2:]}')
print(f'切片3-7:{msn[3:7]}')
print(f'切片3-7,步长为2:{msn[3:7:2]}')
print(f'切片3-最后,步长为2:{msn[3::2]}')
**了解即可**
print(f'切片所有:{msn[:]}')
print(f'反转所有:{msn[::-1]}')
print(f'切片-2--8:{msn[-8:-2:1]}')
print(f'切片8--2:{msn[2:8:1]}')
>>>切片2-最后:llo chd
>>>切片3-7:lo c
>>>切片3-7,步长为2:l 
>>>切片3-最后,步长为2:l h
**了解即可**
>>>切片所有:hello chd
>>>反转所有:dhc olleh
>>>切片-2--8:ello c
>>>切片8--2:llo ch
3.长度len
# str长度
msn = 'hello chd'
#      012345678    # 索引序号
print(len(msn))
>>>9

4.删除字符串前后多余空白 strip()
# str移除空白strip()
name = '   chuid   '
print(name)
# rstrip()方法,删除字符串后的多余空白
print(name.rstrip())
# 要永久删除字符串后多余空白,需将操作方法后的结果存回变量中
name=name.rstrip()
print(name.rstrip())
# 要永久删除字符串前多余空白,需将操作方法后的结果存回变量中
name=name.lstrip()
print(name)
# 要永久删除字符串前后多余空白,需将操作方法后的结果存回变量中
name=name.strip()
print(name)
>>>   chuid   
>>>   chuid
>>>   chuid
>>>chuid
>>>chuid

5.成员运算in和not in
# str成员运算
msn = 'my name is chuid, chuid humor'
print(f'"chuid" in msn:{"chuid" in msn}')
print(f'"chd" not in msn:{"chd" not in msn}')
print(f'not "chd" in msn:{not "chd" in msn}')
>>>"chuid" in msn:True
>>>"chd" not in msn:True
>>>not "chd" in msn:True

6.切分split
# str切分split
info = 'chd:man:27'
info_list1 = info.split(':')
info_list2 = info.split(':',1)
print(f'info_list1:{info_list1}')
print(f'info_list2:{info_list2}')
>>>info_list1:['chd', 'man', '27']
>>>info_list2:['chd', 'man:27']

7.循环
msn = 'hello chd'
for i in msn:
    print(i)
>>>h
>>>e
>>>l
>>>l
>>>o
>>> 
>>>c
>>>h
>>>d

例子1:
for i in range(5):
    print(i)
>>>0
>>>1
>>>2
>>>3
>>>4

8.lstrip() & rstrip()
# str 之lstrip()和rstrip()
name = '   chuid   '
# strip()方法可以返回一个新的字符串,去掉原字符串左右两边的空白字符
print(name.strip())
# rstrip()方法可以返回新的字符串,去掉类字符串右边的空白字符
print(name.rstrip())
# lstrip()方法可以返回新的字符串,去掉类字符串左边的空白字符
print(name.lstrip())
>>>chuid
>>>   chuid
>>>chuid   

9.lower() & upper()
# str 之lower()和upper()  <将字符串中的小(大)写字母转为大(小)写字母>
name = 'Chd Chuid'
print(f'name.upper():{name.lower()}')
print(f'name.upper():{name.upper()}')
>>>name.upper():chd chuid
>>>name.upper():CHD CHUID

10.startswith() & endswith()
# str之startswith()和endswith()  <用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False>
name = 'chd chuid'
print(f'name.startswith("chd"):{name.startswith("chd")}')
print(f'name.endswith("Chuid"):{name.endswith("Chuid")}')
>>>name.startswith("chd"):True
>>>name.endswith("Chuid"):False

11.rsplit()
# str之rsplit()  <通过指定分隔符对字符串进行切片,如果参数n有指定值,则分隔 n+1个子字符串>
info = 'chd:man:27'
print(f'info.rsplit(":",1):{info.rsplit(":",1)}')
>>>info.rsplit(":",1):['chd:man', '27']

12.join()
# str之join() <用于将序列中的元素以指定的字符连接生成一个新的字符串>
list = ['chuid','man','27']
print(f'":".join(list):{":".join(list)}')
>>>":".join(list):chuid:man:27

13.replace()
# str之reolace() <把字符串中的旧字符串替换成新字符串>
name = 'chd chuid'
print(f'name.replace("chuid","mature"):{name.replace("chuid","mature")}')
>>>name.replace("chuid","mature"):chd mature

14.isdigit()
# str之isdigit() <检测字符串是否只由数字组成>
number = '123'
print(number.isdigit())
number = '123.1'
print(number.isdigit())
>>>True
>>>False

例子:
age = input('age: ')
if age.isdigit():
    age = int(age)
    if age < 25:
        print("小姐姐")
    else:
        print('阿姨好')
>>> age: 25
>>> 小姐姐


其他操作
1.find()、rfind()、index()、rindex()、count()
2.center()、ljust()、rjust()、zfill()
3.expandtabs()
4.captalize()、swapcase()、title()
5.is数字系列(判断是否为数字时除了中文数字以后使用isdigit()即可)
	isdecimal():检查字符串是否值包含十进制字符,如果是返回True,否则返回False
	isdigit():如果字符串只包含数字则返回True,否则返回False
	isnumeric():如果字符串中只包含数字字符,则返回True,否则返回False
6.is其他
	isalnum():如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False
	isalpha():如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False
	islower():如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写)字符都是小写,则返回True,否则返回False
	isspace():如果字符串中只包含空白,则返回True,否则返回False
	isupper():如果字符串中包含至少一个区分大小写的字符,并且所有这种(区分大小写)字符都是大写,则返回True,否则返回False
	istitle():如果字符串是标题类型的(见title()),则返回True,否则返回False

列表类型内置方法(list)
作用:多个装备、多个爱好、多门课程…
定义:[]内可以有多个任意类型的值,逗号分隔元素
class_schedule = list(['Chinese','Math','English','Physics','Chemistry'])
print(f"class_achedule:{class_schedule}")
>>> class_achedule:['Chinese', 'Math', 'English', 'Physics', 'Chemistry']

1.按索引取(正向取值 + 反向取值),即可存也可取
name_list = ['chd','chuid','anivd']
name_list[1] = 'chuid humor'
print(f'name_list[1]:{name_list[1]}')
>>> name_list[1]:chuid humor
2.切片
name_list = ['chd','chuid','anivd']
print(f'name_list[0:3:2]:{name_list[0:3:2]}')
>>> name_list[0:3:2]:['chd', 'anivd']

3.长度len
name_list = ['chd','chuid','anivd']
print(f'len(name_list):{len(name_list)}')
>>> len(name_list):3

4.成员运算in和not in
name_list = ['chd','chuid','anivd']
print(f"'chd' in name_list:{'chd' in name_list}")
print(f"'anivd' not in name_list:{'anivd' not in name_list}")
>>> 'chd' in name_list:True
>>> 'anivd' not in name_list:False

5.追加append
name_list = ['chd','chuid','anivd']
name_list.append('chen')
print(f'name_list:{name_list}')
>>> name_list:['chd', 'chuid', 'anivd', 'chen']

6.删除del
name_list = ['chd','chuid','anivd','chen']
del name_list[3]
print(f'name_list:{name_list}')
>>> name_list:['chd', 'chuid', 'anivd']

7.循环
name_list = ['chd','chuid','anivd']
for name in name_list:
    print(name)
>>> chd
>>> chuid
>>> anivd

8.insert() <在...前面插入值>
name_list = ['chd','chuid','anivd']
name_list.insert(1, 'mature')
print(f'name_list:{name_list}')
>>> name_list:['chd', 'mature', 'chuid', 'anivd']

9.pop()  <用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。>
name_list = ['chd','chuid','anivd']
print(f'name_list:{name_list}')
print(f'name_list.pop(1):{name_list.pop(1)}')
>>> name_list:['chd', 'chuid', 'anivd']
>>> name_list.pop(1):chuid
10.remove()  <删除>
name_list = ['chd','chuid','anivd']
print(f'nsme_list.remove("anivd"):{name_list.remove("anivd")}')
print(f'name_list:{name_list}')
>>> nsme_list.remove("anivd"):None
>>> name_list:['chd', 'chuid']

11.count() <用于统计字符串里某个字符出现的次数>
name_list = ['chd','chuid','anivd']
print(f"name_list.count('chd'):{name_list.count('chd')}")
>>> name_list.count('chd'):1

12.index()   <显示索引值>
name_list = ['chd','chuid','anivd']
print(f"name_list.index('chd'):{name_list.index('chd')}")
print(f"name_list.index('chuid'):{name_list.index('chuid')}")
>>> name_list.index('chd'):0
>>> name_list.index('chuid'):1

13.clear()   <清空列表内的值>
name_list = ['chd','chuid','anivd']
name_list.clear()
print(f"name_list:{name_list}")
>>> name_list:[]

14.copy() <返回一个字典的浅复制>
name_list = ['chd','chuid','anivd']
print(f'name_list:{name_list}')
print(f"name_list.copy():{name_list.copy()}")
>>> name_list:['chd', 'chuid', 'anivd']
>>> name_list.copy():['chd', 'chuid', 'anivd']

15.extend()   <合并列表>
name_list = ['chd','chuid','anivd']
name_list1 = ['chen']
name_list.extend(name_list1)
print(f'name_list:{name_list}')
>>> name_list:['chd', 'chuid', 'anivd', 'chen']

16.reverse()  <列表内排序倒置>
name_list = ['chd','chuid','anivd']
name_list.reverse()
print(f'name_list:{name_list}')
>>> name_list:['anivd', 'chuid', 'chd']

17.sort() <用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。>
name_list = ['chd','chuid','anivd']
name_list.sort()
print(f'name_list:{name_list}')
name_list.sort(reverse=True)
print(f'name_list_reverse:{name_list}')
>>> name_list:['anivd', 'chd', 'chuid']
>>> name_list_reverse:['chuid', 'chd', 'anivd']

*** 可变数据类型、多个值、有序 ***
name_list = ['chd','chuid','anivd']
print(f'first:{id(name_list)}')
name_list[2] = ''
print(f'second:{id(name_list)}')
>>> first:4022920
>>> second:4022920
元组类型内置方法(tuple)
元组是不可变的列表,即元组的值不可更改,因此元组一般只使用于只存不取的需求。也因此元组可以被列表取代掉,所以元组相比较列表的优点为:列表的值修改后,列表的结构将会发生改变,而元组只需要存储,因此列表在某种程度上而言需要占用更多的内存。但是目前工业上内存已经不是问题了,所以工业上元组一般不会使用。
作用:多个装备、多个爱好、多门课程
定义:在()内可以有多个任意类型的值,逗号分隔元素
*** 可以存多个值、有序、不可变类型 ***

例子1:
my_friend = tuple(('chd','chuid','anivd'))
print(f'my_friend:{my_friend}')
>>> my_friend:('chd', 'chuid', 'anivd')

例子2:
name_str = ('egon')
name_tuple = ("egon",)
print(f'type(name_str):{type(name_str)}')
print(f'type(name_tuple):{type(name_tuple)}')
>>> type(name_str):<class 'str'>
>>> type(name_tuple):<class 'tuple'>

1.索引取值
name_list = ['chd','chuid','anivd','chen']
print(f'name_list[0]:{name_list[0]}')
>>> name_list[0]:chd

2.切片
name_list = ['chd','chuid','anivd','chen']
print (f'name_list[1:3:2]:{name_list[1:3:2]}')
>>> name_list[1:3:2]:['chuid']

3.长度len
name_list = ['chd','chuid','anivd','chen']
print(f'len(name_list):{len(name_list)}')
>>> len(name_list):4

4.成员运算in和not in
name_list = ['chd','chuid','anivd','chen']
print(f'"chuid" in name_list:{"chuid" in name_list}')
>>> "chuid" in name_list:True

5.循环
name_list = ['chd','chuid','anivd','chen']
for name in name_list:
    print(name)
>>> chd
>>> chuid
>>> anivd
>>> chen
6.count() <用于统计字符串里某个字符出现的次数>
name_list = ['chd','chuid','anivd','chen']
print(f'name_list.count("chuid"):{name_list.count("chuid")}')
>>> name_list.count("chuid"):1

7.index() <检测字符串中是否包含子字符串 str>
name_list = ['chd','chuid','anivd','chen']
print(f'name_list("chd"):{name_list.index("chd")}')
>>> name_list("chd"):0


元组和列表的区别
元组不可改变的原因是:索引所对应的值的内存地址是不可改变的,或者反过来说:只要索引对应值的内存地址没有改变,那么元组是始终没有改变的
i = (['a','b','c','d'],'chd','chuid')
print(f'id(i[0]):{id(i[0])}')
print(f'id(i[1]:{id(i[1])}')
print(f'id(i[2]):{id(i[2])}')

i1 = 'A'
print(f'i1:{i1}')
print(f'id(i[0]):{id(i[0])}')
print(f'i:{i}')
>>> id(i[0]):33972872
>>> id(i[1]:34432984
>>> id(i[2]):34462328
>>> i1:A
>>> id(i[0]):33972872
>>> i:(['a', 'b', 'c', 'd'], 'chd', 'chuid')

列表可变的原因是:索引所对应的值的内存地址是可以改变的
i = ['a','b','c','d']
print(f'id(i[0]):{id(i[0])}')
i1 = 'A'
print(f'id(i1):{id(i1)}')
>>> id(i[0]):4234352
>>> id(i1):4381304


字典类型内置方法(dic)
作用:存多个值,但每一个值都有一个key与之对应,key对值有描述功能。多用于存的值表示的是不同的状态时,
			 	  例如:存的值有姓名、年龄、身高、体重、爱好。

定义:{}内用逗号分隔开多个元素,每一个元素都是key:value的形式,value可以是任意数据类型,而key通常应该是字符串类型,但是key必须为不可变类型。

*** 可变数据类型、无序、多个值(值可以是多个类型,key必须是不可变类型,通常应该是不可变类型中的字符串类型)***


dic = {'a':1,'b':2}
print(f'dic:{dic}')
>>> dic:{'a': 1, 'b': 2}

dic = dict(a=1,b=2,c=3)
print(f'dic:{dic}')
>>> dic:{'a': 1, 'b': 2, 'c': 3}

dic ={0:'a',1:'b'}
print(f'dic[0]:{dic[0]}')
>>> dic[0]:a

1.按key存取值:可存可取
dic = {'a':1,'b':2}
print(f'first dic["a"]:{dic["a"]}')
>>> first dic["a"]:1

dic['a'] =3
print(f'second dic["a"]:{dic["a"]}')
print(dic)
>>> second dic["a"]:3
>>> {'a': 3, 'b': 2}

2.删除del
# dic 之删除del
dic ={'a':1,'b':2}
del dic['a']
print(dic)
print(f'dic.get("a"):{dic.get("a")}')
>>> {'b': 2}
>>> dic.get("a"):None

# dic 之删除pop()
dic ={'a':1,'b':2}
dic.pop("a")
print(f"dic.pop('b'):{dic.pop('b')}")

print(f'dic.get("a"):{dic.get("a")}')
>>> dic.pop('b'):2
>>> dic.get("a"):None

# dic 之删除popitem()
dic ={'a':1,'b':2}
print(f'dic.popitem():{dic.popitem()}')  # popitem()方法随机返回并删除字典中的一对键和值(一般删除末尾对)。
>>> dic.popitem():('b', 2)

3.长度len
dic = {'a':1,'b':2}
print(f'len(dic):{len(dic)}')
>>> len(dic):2

4.成员运算in和not in
dic ={'a':1,'b':2}
print(f"'a' in dic:{'a' in dic}")
print(f'1 in dic:{1 in dic}')
>>> 'a' in dic:True
>>> 1 in dic:False

5.键keys()、值values()、键值对items()
# dic之键keys()、值values()、键值对items()
dic = {'a':1,'b':2}
print(f'dic.keys():{dic.keys()}')
print(f'dic.values():{dic.values()}')
print(f'dic.items():{dic.items()}')
>>> dic.keys():dict_keys(['a', 'b'])
>>> dic.values():dict_values([1, 2])
>>> dic.items():dict_items([('a', 1), ('b', 2)])

6.循环
dic = {'a':1,'b':2,'c':3,'d':4}
for key,value in dic.items():
    print(key,value)
>>> a 1
>>> b 2
>>> c 3
>>> d 4

7.get() <返回指定键的值>
dic = {'a':1,'b':2}
print(f'dic.get("a"):{dic.get("a")}')
print(f'dic.get("c"):{dic.get("c")}')
>>> dic.get("a"):1
>>> dic.get("c"):None
8.update() <把字典dict2的键/值对更新到dict里>
dic1 = {'a':1,'b':2}
dic2 = {'c':3}
dic1.update(dic2)
print(f'dic1:{dic1}')
>>> dic1:{'a': 1, 'b': 2, 'c': 3}

9.fromkeys() <用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值>
dic = dict.fromkeys(['chd','chuid','anivd'],1)
print(f'dic:{dic}')
>>> dic:{'chd': 1, 'chuid': 1, 'anivd': 1}

10.setdefault() <和get()方法类似,如果键不存在于字典中,将会添加键并将值设为默认值>
dic = {'a':1,'b':2}
print(f'dic.setdefault("a"):{dic.setdefault("a",3)}')
print(f'dic:{dic}')
print(f'dic.setdefault("c"):{dic.setdefault("c",3)}')
print(f'dic:{dic}')
>>> dic.setdefault("a"):1
>>> dic:{'a': 1, 'b': 2}
>>> dic.setdefault("c"):3
>>> dic:{'a': 1, 'b': 2, 'c': 3}


集合类型内置方法(set)
集合可以理解成一个集合体,学习Python的人是一个集合体,学习Linux的人是一个集合体。
Python = ['chd','chuid','anivd','chen']
Linux = ['chd','zhang','wang']
Python_Linux_list = []
for stu in Python:
    if stu in Linux:
        Python_Linux_list.append(stu)
print(f'Python and Linux:{Python_Linux_list}')
>>> Python and Linux:['chd']
作用:用于关系运算的集合体,由于集合内的元素无序且集合元素不可重复,因此集合可以去重,但是去重后的集合会打乱原来元素的顺序。
定义:{}内用逗号分隔开多个元素,每个元素必须是不可变类型。
i = {1,2,3,2,'a'}
print(f'i:{i}')
>>> i:{1, 2, 3, 'a'}

i = {1,3,2,'a','c'}
for s in i:
    print(s)
>>> 1
>>> 2
>>> 3
>>> a
>>> c
i = set('chuid')
print(f'i:{i}')
>>> i:{'u', 'c', 'i', 'd', 'h'}

1.长度len
i = {1,2,'abc'}
print(f'len(s):{len(i)}')
>>> len(s):3

2.成员运算符in和not in
i = {1,2,'abc'}
print(f'1 in i:{1 in i}')
print(f'a in i:{"a" in i}')
>>> 1 in i:True
>>> a in i:False

3.|并集、union
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
print(f'python|linux:{python|linux}')
print(f'python.union(linux):{python.union(linux)}')
>>> python|linux:{'chd', 'chen', 'zhang', 'anivd', 'wang', 'chuid'}
>>> python.union(linux):{'chd', 'chen', 'zhang', 'anivd', 'wang', 'chuid'}

4.&交集、intersection
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
print(f'python&linux:{python&linux}')
print(f'python.intersection(linux):{python.intersection(linux)}')
>>> python&linux:{'chen'}
>>> python.intersection(linux):{'chen'}

5.-差集、difference
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
print(f'python-linux:{python-linux}')
print(f'python.difference(linux):{python.difference(linux)}')
>>> python-linux:{'anivd', 'chd', 'chuid'}
>>> python.difference(linux):{'anivd', 'chd', 'chuid'}

6.^对称差集、symmetric_difference
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
print(f'python^linux:{python^linux}')
print(f'python.symmetric_difference(linux):{python.symmetric_difference(linux)}')
>>> python^linux:{'chd', 'zhang', 'wang', 'anivd', 'chuid'}
>>> python.symmetric_difference(linux):{'chd', 'zhang', 'wang', 'anivd', 'chuid'}

7.==
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
java = {'zhang','chen','wang'}
print(f'python==linux:{python==linux}')
print(f'java==linux:{java==linux}')
>>> python==linux:False
>>> java==linux:True

8.父集:>、>=、issuperset
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
java = {'chd','chuid'}
print(f'python>linux:{python>linux}')
print(f'python>=linux:{python>=linux}')
print(f'python>=java:{python>=java}')
print(f'python.issuperset(java):{python.issuperset(java)}')
>>> python>linux:False
>>> python>=linux:False
>>> python>=java:True
>>> python.issuperset(java):True

9.子集:<、<=、issubset
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
java = {'chd','chuid'}
print(f'python<linux:{python<linux}')
print(f'python<=linux:{python<=linux}')
print(f'java.issubset(java):{java.issubset(java)}')
>>> python<linux:False
>>> python<=linux:False
>>> java.issubset(java):True

10.add() <添加>
i = {1,2,'a'}
i.add(3)
print(i)
>>> {1, 2, 3, 'a'}

11.remove() <删除>
i = {1,2,'a'}
i.remove(2)
print(i)
>>> {1, 'a'}

12.difference_update() <用于移除两个集合中都存在的元素>
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
python.difference_update(linux)
print(f'python.difference_update(linux):{python}')
>>> python.difference_update(linux):{'chuid', 'chd', 'anivd'}

13.discard() <用于移除指定的集合元素。remove()方法在移除一个不存在的元素时会发生错误,而discard()方法不会>
i = {1,2,'a'}
i.discard(3)
print(i)
>>> {'a', 1, 2}

14.isdisjoint()  <用于判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False>
# set之isdisjoint()集合没有共同的部分返回True,否则返回False
python = {'chd','chuid','anivd','chen'}
linux = {'zhang','chen','wang'}
python.isdisjoint(linux)

print(f'python.isdisjoint(linux):{python.isdisjoint(linux)}')
>>> python.isdisjoint(linux):False

*** 多个值(且值为不可变类型)***
i = {1,2,'a'}
print(f'first:{id(i)}')
i.add(3)
print(f'second:{id(i)}')
>>> first:31885576
>>> second:31885576

*** 无序、可变数据类型***
stu_info_list1 = []
for stu_info in stu_info_list:
    if stu_info not in stu_info_list1:
        stu_info_list1.append(stu_info)
for stu_info1 in stu_info_list1:
    print(stu_info1)
>>> {'name': 'chd', 'age': 27, 'sex': 'man', 'height': 171, 'weight': 130}
>>> {'name': 'chd', 'age': 26, 'sex': 'man', 'height': 170, 'weight': 128}
>>> {'name': 'chd', 'age': 25, 'sex': 'man', 'height': 170, 'weight': 126}


数据类型分类
1.按存值个数区分
 
2.按可变不可变区分
 
3.按有序无序区分
 
4.按访问类型区分
 


字符编码

 
乱码分析
概念:
文件从内存放到硬盘的操作简称存文件
文件从硬盘读到内存的操作简称读文件
乱码的两种情况:
乱码一:存文件时就已经乱码
乱码二:存文件时不乱码而读文件时乱码
总结
1、保证不乱码的核心就是:字符按照上面标准而编码的,就要按照上面标准编码(此处的标准指的就是字符编码)
2、在内存中写的所有字符,都是Unicode编码,内存中固定使用的是Uncidoe编码,我们唯一能改变的是存储到硬盘时使用的编码。
Unicode ---> encode(编码)---> gbk
Unicode <---decode(解码)<---- gbk


读文件:decode	保存文件:encode


 

标签:chuid,chd,name,Python,list,笔记,dic,入门篇,print
来源: https://blog.csdn.net/C_huid/article/details/116021833

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有