Python 学习

您所在的位置:网站首页 python中5种简单的数据类型 Python 学习

Python 学习

2023-04-22 23:02| 来源: 网络整理| 查看: 265

第一章 起步1.变量1.1 变量规范1.2 例子第二章 变量和简单数据类型python常用的内置数据类型Python中有3种不同的数字类型2.字符串2.1 使用方法修改字符串大小写2.2 合并(拼接)字符串2.3 使用制表符或换行符添加空白2.4 删除空白3.数字3.1 整数Booleam类型:3.2 浮点数3.3 使用函数str()避免类型错误3.4 python 2中的整数4.注释第三章 列表简介3.1 列表的含义3.1.1 访问列表元素3.1.2 索引从0而不是1开始3.1.3 使用列表中的各个值3.2 修改、添加和删除元素3.2.1 修改列表元素3.2.2 在列表中添加元素3.2.3 从列表中删除元素3.3组织列表3.3.1 使用方法sort()对列表进行永久排序3.3.2 使用sorted()对列表进行临时排序3.3.3 倒着打印列表3.3.4 确定列表的长度3.4 使用列表时避免索引错误第四章 操作列表4.1 遍历整个列表4.1.1 深入地研究循环4.1.2 在for循环中执行更多的操作4.1.3 在for循环结束后执行一些操作4.2 避免缩进错误4.2.1 忘记缩进4.2.2 忘记缩进额外的代码行4.3 创建数值列表4.3.1 使用函数range()4.3.2 使用range()创建数字列表4.3.3 对数字列表执行简单的统计计算4.3.4 列表解析4.4 使用列表的一部分4.4.1 切片4.4.2 遍历切片4.4.3 复制列表4.5 元组4.5.1 定义元组4.5.2 遍历元组中所有的值4.5.3 修改元组变量4.6 代码格式4.6.1 格式设置指南4.6.2 缩进4.6.3 行长4.6.4 空行4.6.5 其他格式设置指南第五章 if语句5.1 简单示例5.2 条件测试5.2.1 检查是否相等5.2.2 检查是否相等时不考虑大小写5.2.3 检查是否不相等5.2.4 比较数字5.2.5 检查多个条件5.2.6 检查特定值是否包含在列表中5.2.7 检查特定值是否不包含在列表中5.2.8 布尔表达式5.3.1 简单的if语句5.3.2 if-else语句5.3.3 if-elif-else语句5.3.4 使用多个elif5.3.6 测试多个条件5.4 使用if语句处理列表5.4.1 检查特殊元素5.4.2 确定列表不为空5.4.3 使用多个列表5.5 设置if语句的格式第六章 字典6.1 一个简单的字典6.2 使用字典6.2.1 访问字典中的值6.2.2 添加键—值对6.2.3 先创建一个空字典6.2.4 修改字典中的值6.2.5 删除键-值对6.2.6 由类似对象组成的字典6.3 遍历字典6.3.1 遍历所有的键-值对6.3.2 遍历字典中的所有键6.3.3 按顺序遍历字典中的所有键6.3.4 遍历字典中的所有值6.4 嵌套6.4.1 字典列表6.4.2 在字典中存储列表6.4.3 在字典中存储字典第七章 用户输入和while循环7.1 函数input()的工作原理7.1.1 编写清晰的程序7.1.2 使用int()来获取数值输入7.1.3 求模运算符7.2 while循环简介7.2.1使用while 循环7.2.2 让用户选择何时退出7.2.3 使用标志7.2.4 使用break退出循环7.2.5 在循环中使用continue7.2.6 避免无限循环7.3 使用while循环来处理列表和字典7.3.1 在列表之间移动元素7.3.2 删除包含特定值的所有列表元素7.3.3 使用用户输入来填充字典第八章 函数8.1 定义函数8.1.1 向函数传递信息8.1.2 实参和形参8.2 传递实参8.2.1 位置实参8.2.2 关键字实参8.2.3 默认值8.2.4 等效的函数调用8.2.5 避免实参错误8.3 返回值8.3.1 返回简单值8.3.2 让实参变成可选的8.3 返回字典8.3.4 结合使用函数和while循环8.4 传递列表8.4.1 在函数中修改列表8.2.4 禁止函数修改列表8.5 传递任意数量的实参8.5.1 结合使用位置实参和任意数量实参8.5.2 使用任意数量的关键字实参8.6 将函数存储在模块中8.6.1 导入整个模块8.6.2 导入特定的函数8.6.3 使用as给函数指定别名8.6.4 使用as给模块指定别名8.6.5 导入模块中的所有函数8.7 函数编写指南第九章 类9.1 创建和使用类9.1.1 创建Dog类1 定义了一个名为Dog的类。在Python中,首字母大写的名称指的是类。类定义中的括号为空—要从空白创建这个类

第一章 起步

1.变量

1.1 变量规范 只能包含字母、数字、下划线。可以字母或下划线作为开头,而不能用数字 变量名不能包含空格

1.2 例子message = "hello python world!"print(message)

添加一个名为message的变量,并且存储了为“Hello python world”的文本值

第二章 变量和简单数据类型

python常用的内置数据类型

Number(数字)、String(字符串)、List(列表)、Tuple(元组)、Set(集合)、Dictionary(字典)

Python中有3种不同的数字类型

int(整型)、float(浮点型)、complex(复数类型)

2.字符串

“This is a string.”

‘This is also a string’

2.1 使用方法修改字符串大小写name = '"ada lovelace"print(name.title()) #首字母大写方法

输出Ada Lovelace

print(name.upper()) #全大写方法

输出 ADA LOVELACE

print(name.lower()) #全小写方法

输出ada lovelace

2.2 合并(拼接)字符串first_name = 'ada'last_name = 'lovelace'full_name = first_name + ' ' + last_name #使用 + 来合并字符串print (full_name)print("Hello , " + full_name.title() + "!")#通过合并字符串(拼接)使用存储在变量中的信息来创造完整的消息message = "hello , " + full_name.title() + "!"#可以将拼接创造的消息存储在变量中打印出print(message)

2.3 使用制表符或换行符添加空白

\t 制表符

print("python")#输出#pythonprint("\tPython")#输出# python

\n换行符

print("Languages:\nPython\nC\nJavaScript")#输出# Languages:# Python# C# JavaScript

2.4 删除空白

确保字符串末尾没有空白——使用方法rstrip(),调用方法时多余的空格被删除,但是删除只是暂时的。

favorite_language = 'python 'print(favorite_language.rstrip())

输出:python

删除字符串开头lstrip()、两端strip()的空白

favorite_language = ' python 'print(favorite_language.rstrip())

' python'

print(favorite_language.lstrip()) #去头

'python '

print(favorite_language.strip()) #去两端

'python'

3.数字

3.1 整数

可以使用不同的进制来表示

不加任何前缀为十进制整数 加前缀0o为八进制整数 加前缀0x则为十六进制整数加减乘除: print(2+3)

5

print(3-2)

1

print(3 * 2)

6

print(3 / 2)

1.5

乘方运算

print(3 ** 2)

9

print(3 ** 3)

27

Booleam类型:

整型的子类型

使用函数可将其他类型的数据转为布尔类型,当给bool函数传入下列参数时将其返回false

3.2 浮点数

python中,带小数点的数字都称为浮点数(使用C语言中的double类型实现)

但包含小数位数可能是不确定的

print(0.2 + 0.1)

0.300000000000004

3.3 使用函数str()避免类型错误age = 23message = "Happy " + str(age) + "rd Birthday!"print(message)

将数值23转换为字符串

3.4 python 2中的整数print(3 / 2)

1

返回的结果为1,而不是1.5。Python2中整数除法的结果只包含整数部分,小数部分被删除,计算整数结果时,将小数部分直接删除

要避免这种情况,必需一个操作数是浮点数

print(3.0 / 2)

1.5

4.注释

注释用井号(#)标识,井号后的内容都会被解释器忽略

# 向大家问好

第三章 列表简介

3.1 列表的含义

列表: 由一系列按特定顺序排列的元素组成

用方括号([])来表示列表,并用逗号来分割其中的元素

bicycles = [ 'trek' , 'cannondale' , 'redline' , ' specialized ']print(bicycles) #打印出列表,包含方括号['trek' , 'cannondale' , 'redline' , 'specialized ']

3.1.1 访问列表元素

指出列表的名称,再指出元素的索引,并将其放在方括号中

bicycles = [ 'trek' , 'cannondale' , 'redline' , ' specialized ']print(bicycles[0])trek##输出trekprint(bicycles[0].title()) #让trek的格式更整洁

3.1.2 索引从0而不是1开始

访问索引1和3处的自行车

bicycles = ['trek', 'cannodale ', 'redline' ,'specialized' ]print(bicycles[1])print(bicycles[3])

3.1.3 使用列表中的各个值bicycles = ['trek', 'cannodale ', 'redline' ,'specialized' ]message = "My first bicycle was a " + bicycles[0].title() + "."print(message)

使用bicycles[0]的值生成了一个句子,并将其存储在变量message中

输出My first bicycle was a trek

3.2 修改、添加和删除元素

3.2.1 修改列表元素

有一个摩托车列表,其中的第一个元素为’honda’,计划进行修改

motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]print(motorcycles)motorcycles[0] = ' ducati 'print(motorcycles)

输出结果分别为

[‘honda’ , ‘yamaha’ , ‘suzuki’]

[‘ducati’ ,’ yamaha’ , ‘suzuki’]

3.2.2 在列表中添加元素

1.在列表末尾添加元素

motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]print(motorcycles)motorc.append(' ducati ')print(motorcycles)

输出结果

[‘honda’ , ‘yamaha’ , ‘suzuki’]

[‘honda’ , ‘yamaha’ , ‘suzuki’ , ‘ducati’]

方法append()将元素添加到了列表末尾,而不影响列表中的其他元素

2.在列表中插入元素

motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]motorcycles.insert(0, 'ducati)motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]

输出结果

[‘ducati’ , ‘honda’ ,’yamaha’ , ‘suzuki’]

3.2.3 从列表中删除元素

1.使用del语句删除元素

知道删除的元素在列表中的位置,使用del语句

motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]print(motorcycles)del motorcycles[0]#使用del删除了列表中的第一个元素'honda'print(motorcycles)

输出结果

[ ‘honda’ , ‘yamaha’ , ‘suzuki’ ]

[’yamaha‘ , ‘suzuki ‘]

使用del语句进行删除后,再也无法访问该值

2.使用方法pop()删除元素

方法pop()可删除列表末尾的元素,并让你能够接着使用它

下面从列表中弹出一款摩托车

motorcycles = [ 'honda' , 'yamaha' , 'suzuki' ]print(motorcycles)#打印列表popped_motorcycles = motorcycles.pop()#弹出一个值,并将其存储到popped_motorcycle中print(motorcycles)#打印表,证实从中删除了一个值print(popped_motorcycle)#打印弹出的值,以证明依然能够访问到被删除的值

输出结果

[‘honda’ , ‘yamaha’ ,’suzuki’]

[‘honda’ ,’ yamaha’]

suzuki

假设列表中摩托车按购买时间排列,就可使用方法pop()打印一条消息,指出最后购买的是哪款摩托车

motorcycles = ['honda' , 'yamaha' , 'suzuki']last_owned = motorcycles.pop()print("The last motorcycle I owned was a " + last_owned.title + ".")

输出结果

The last motorcycle I owned was a Suzuki

3.弹出列表中任何位置处的元素

用pop(n),删除列表中位于第n+1个位置的元素

motorcycles = ['honda' , 'yamaha' , 'suzuki']first_owned = motorcycles.pop(0)print("The first motorcycle I owned was a " + last_owned.title + ".")

输出结果

The first motorcycle I owned was a Honda

总结:直删不用用del,删了还用用pop()

4.根据值删除元素

只知道要删除的元素的值,使用方法remove()

eg:在列表中删除值’ducati’

motorcycles = ['honda' , 'yamaha' , 'suzuki','ducati']motorcycles.remove('ducati')print(motorcycles)

输出结果

[‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]

[‘honda’, ‘yamaha’, ‘suzuki’]

使用remove()删除元素时,可以接着使用它的值

motorcycles = ['honda' , 'yamaha' , 'suzuki','ducati']#定义列表print(motorcycles)too_expensive = 'ducati'#将'ducati'存储到too_expensive中motorcycles.remove(too_expensive)#删除列表中的ducatiprint(motorcycles)print('\nA ' + too_expensive.title() + " is too expensive for me.")

输出结果

[‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]

[‘honda’, ‘yamaha’, ‘suzuki’]

A Ducati is too expensive for me.

remove()只删除第一个指定的值

3.3组织列表

以特定的顺序呈现信息、保留聊表元素最初的排列顺序

3.3.1 使用方法sort()对列表进行永久排序

按字母顺序进行排列

cars = ['bmw' , 'audi' , 'toyota' , 'subaru']cars.sort()print(cars)

方法sort()永久性地改变了列表元素的排列顺序

输出结果

[‘audi’, ‘bmw’, ‘subaru’ ,’toyota’]

按与字母相反顺序来排列列表元素

cars = ['bmw' , 'audi' , 'toyota' , 'subaru']cars.sort(reverse=True)print(cars)

输出结果

[‘toyota’, ‘subaru’, ‘bmw’, ‘audi’]

3.3.2 使用sorted()对列表进行临时排序

保留列表元素原来的排列顺序,同时以特定的顺序呈现 使用函数sorted()

cars = ['bmw', 'audi', 'toyota', 'subaru'] print("Here is the original list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) #临时排序print("\nHere is the original list again:") print(cars

输出结果

Here is the original list:

[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]

Here is the sorted list:

[‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]

Here is the original list again:

[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]

3.3.3 倒着打印列表

翻转列表元素的排序顺序,使用方法reverse()

cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.reverse()print(cars)

输出结果

[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]

[‘subaru’, ‘toyota’, ‘audi’, ‘bmw’]

reverse()不是按字母顺序相反的顺序进行排列,而是反转列表元素的排列顺序,且永久的修改排列顺序,但随时可恢复到原来的排列顺序

3.3.4 确定列表的长度

使用函数len()可快速获悉列表长度

cars = ['bmw' , 'audi' , 'toyota' ,'subaru']len(cars)

4

3.4 使用列表时避免索引错误

需要访问最后一个列表元素时,都可以使用索引-1

motorcycles = ['honda' , 'yamaha','suzuki']print(motorcycles[-1])

‘suzuki’

第四章 操作列表

4.1 遍历整个列表

需要对列表中的每个元素都执行相同的操作时,可使用Python的for循环

eg: 使用for循环来打印魔术师名单中的所有名字:

magicians = ['alice', 'david' , 'carolina']for magician in magicians: #定义一个for循环,从列表magicians中取出一个名字,并将其存储在变量magician中 print(magician)#注意空格

输出结果

alice

david

carolina

4.1.1 深入地研究循环

在前面的magicians.py中使用的简单循环中,Python将首先读取其中的第一行代码:

for magician in magicians:

这行代码让Python获取列表magicians 中的第一个值(’alice’ ),并将其存储到变量magician 中。接下来,Python读取下一行代码:

print(magician)

它让Python打印magician 的值——依然是’alice’ 。鉴于该列表还包含其他值,Python返回到循环的第一行:

for magician in magicians:

Python获取列表中的下一个名字——‘david’ ,并将其存储到变量magician 中,再执行下面这行代码:

print(magician)

Python再次打印变量magician 的值——当前为’david’ 。接下来,Python再次执行整个循环,对列表中的最后一个值——‘carolina’ 进行处理。至此,列表中没有其他的值了,因此Python接着执行程序的下一行代码。在这个示例中,for 循环后面没有其他的代码,因此程序就此结束。

对列表中的每个元素,都将执行循环指定的步骤,而不管列表包含多少个元素。如果列表包含一百万个元素,Python就重复执行指定的步骤一百万次, 且通常速度非常快。

4.1.2 在for循环中执行更多的操作

eg:对于每位魔术师,都打印一条消息:

magicians = ['alice' , 'david' , 'carolina']for magician in magicians:` print(magician.title() + ", that was a great trick!" )

输出结果:

Alice, that was a great trick!

David, that was a great trick!

Carolina, that was a great trick!

4.1.3 在for循环结束后执行一些操作

在for循环结束后,需提供总结性输出或者接着执行程序必须完成的其他任务

magicians = ['alice', 'david', 'carolina']for magician in magicians: print(magician.title() + ", that was a great trick!")` print("I can't wait to see your next trick, " + magician.title() + ".\n")print("Thank you, everyone. That was a great magic show!") #总结性语句

输出结果

Alice, that was a great trick!

I can’t wait to see your next trick, Alice.

David, that was a great trick!

I can’t wait to see your next trick, David.

Carolina, that was a great trick!

I can’t wait to see your next trick, Carolina.

Thank you, everyone. That was a great magic show!

4.2 避免缩进错误

4.2.1 忘记缩进

通常,将紧跟在for 语句后面的代码行缩进,可消除这种缩进错误。

4.2.2 忘记缩进额外的代码行

试图在循环中执行多项任务,却忘记缩进其中的一些代码行时,就会出现这种情况。

例如,如果忘记缩进循环中的第2行代码(它告诉每位魔术师,我们期待他的下一次表演),就会出现这种情况:

4.3 创建数值列表

4.3.1 使用函数range()for value in range (1,5): print(value)

打印结果:

1

2

3

4

range()只是打印数字1~4,函数range()让python从指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出不包含第二个值

需要打印1~5 需要使用range(1,6)

for value in range(1,6) print(value)

打印结果

1

2

3

4

5

4.3.2 使用range()创建数字列表

eg:使用list()将range()的结果直接转换为列表

numbers = list(range(1,6))print(numbers)

结果如下

[1,2,3,4,5]

使用range()时,指定步长。

eg:打印1~10内的偶数

event_numbers = list(range(2,11,2))print(event_numbers)

range()从2开始数,不断的加2,直到达到或超过最终值11

eg:创建一个列表,包含前十个整数的平方

squares = []#创建空列表for value in range(1,11): #让函数range()遍历1~10 square = value**2 #计算当前值的平方,存储到变量square中 squares.append(square) #将新计算的平方值附加到列表squares末尾print(squares) #打印列表squares squares = [] for value in range(1,11): squares.append(value**2) #不使用临时变量square 而直接将每个计算得到的值附加到列表末尾print(squares)

4.3.3 对数字列表执行简单的统计计算digits = [1,2,3,4,5,6,7,8,9,0]print(min(digits)) #输出最小值print(max(digits)) #输出最大值print(sum(digits)) #输出和

4.3.4 列表解析

列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素

squares = [value**2 for value in range(1,11)]print(squares) 先指定一个描述性的列表名 制定一个左方括号,并定义一个表达式(value**2),用于生成存储到列表中的值 编写一个for循环(for value in range(1,11)将值1~10提供给表达式value**2),用于给表达式提供值,再加上右方括号

4.4 使用列表的一部分

处理列表的所有元素

4.4.1 切片

创建切片,可指定使用的第一个元素和最后一个元素的索引,在到达指定的第二个索引前面的元素后停止

player = ['charles','martina','michael','florence','eli']print(player[0:3])#输出第1~3个

输出结果

[‘charles’, ‘martina’, ‘michael’]

只包含三名队员

如果没有制定第一个索引,将从列表开头开始提取:

player = ['charles','martina','michael','florence','eli']print(player[:4])#输出前4个

输出结果

[‘charles’, ‘martina’, ‘michael’, ‘florence’]

让列表终止于列表末尾:

提取从第三个元素到末尾的所有元素,可将起始索引指定为2,并省略终止索引:

player = ['charles','martina','michael','florence','eli']print(player[2:])

输出结果为从第3个元素到列表末尾的所有元素

[‘michael’, ‘florence’, ‘eli’]

输出最后3个元素:

print(player[-3:])

输出结果同上。

4.4.2 遍历切片

遍历列表的部分原始,在for循环中使用切片

eg:遍历前三名队员,并打印他们的名字

players = ['charles','martina','michael','florence','eli']print("Here are the first three palyers on my team:")for player in player[:3]:#只遍历前三名队员 print(player.title())

输出结果:

Here are the first three palyers on my team:CharlesMartinaMichael

4.4.3 复制列表

需要既有列表创建全新的列表

可创建一个包含整个列表的切片:方法为同时省略起始索引和终止索引([:]),创建一个始于第一个元素终于最后一个元素的切片

my_foods = ['pizza','falafel','caroot cake']friend_foods = my_foods[:]print("My favorite foods are:")print(my_foods)print("\nMy friends's favorite foods are:")print(friend_foods)

输出结果:

My favorite foods are:[‘pizza’, ‘falafel’, ‘caroot cake’]

My friends’s favorite foods are:[‘pizza’, ‘falafel’, ‘caroot cake’]

4.5 元组

元组是有序且不可更改的集合。

创建一系列不可修改的元素,不能修改的值-不变的,不可变的列表-元组

4.5.1 定义元组

用圆括号来标识

di = (200,50)print(di[0])print(di[1])

4.5.2 遍历元组中所有的值for d in di: print(d)

4.5.3 修改元组变量

虽然不可修改元组的元素,但可以给存储元组的变量赋值:

重新定义整个元组

di = (200,50)print("Original dimensions: ")for d in di: print(d)di = (400,100)print("\nModified dimensions: ")for ds in di : print(ds)

4.6 代码格式

4.6.1 格式设置指南

代码易于编写/便于阅读->大多数程序员选择便于阅读

4.6.2 缩进

每级缩进都使用四个空格

通常使用制表符而不是空格来进行缩进

4.6.3 行长

建议每行不超过80字符

4.6.4 空行

要讲程序的不同部分分开,使用空行,会影响代码的可读性,根据水平缩进情况来解读代码,不关心垂直间距

4.6.5 其他格式设置指南

PEP 8 – Style Guide for Python Code | peps.python.org

第五章 if语句

5.1 简单示例cars = ['audi','bmw','subaru','toyota']for car in cars: if car == 'bmw': #条件语句,只有宝马首字母大写打印,其他均小写打印 print(car.upper()) else: print(car.title())

输出结果:

AudiBMWSubaruToyota

5.2 条件测试

每条if语句的核心都是一个值为true或者false的表达式——条件测试

条件测试的值为TRUE—执行紧跟在if语句后的代码

条件测试的值为FALSE—忽略这些代码

5.2.1 检查是否相等car = 'bmw'print(car == 'bmw')

输出结果:True

car = 'Audi'print(car == 'bmw')

输出结果:False

5.2.2 检查是否相等时不考虑大小写

检查是否相等时,是区分大小写的

car = 'Bmw'print(car == 'bmw')

输出False

car = 'Bmw'print(car.lower() == 'bmw')

输出True

5.2.3 检查是否不相等

结合使用惊叹号和等号(!=)

requested_topping = "mushrooms"if requested_topping != 'anchovies' : print("Hold the anchovies")

输出Hold the anchovies

5.2.4 比较数字age = 18print(age == 18)

输出ture

还可以检查两个数字是否不等:

answer = 17if answer != 42: print("That is not the correct answer.")

输出That is not the correct answer.

条件语句中可包含各种数学比较,如大于,小于等于、大于、大于等于

age = 19print(age = 21)

输出

TrueTrueFalseFalse

5.2.5 检查多个条件

1.使用and检查多个条件

要检查两个条件都为true,使用关键字and:每个测试都通过—True,如果至少有一个测试没有通过,整个表达式就为False

age_0 = 22age_1 = 18print(age_0 >= 21 and age_1 >=21)age_1 = 22print(age_0 >= 21 and age_1 >=21)

输出

FalseTrue

2.使用or检查多个条件

至少有一个条件满足,就能通过整个测试。仅当两个测试都没通过时,才为false

age_0 = 22age_1 = 18print(age_0 >= 21 or age_1 >=21)age_0 = 18print(age_0 >= 21 or age_1 >=21)

输出

TrueFalse

5.2.6 检查特定值是否包含在列表中

判断特定的值是否已包含在列表中,使用关键字in

requested_topping = ['mushrooms','onions','pineapple']print('mushrooms' in requested_topping)print('pepperoni' in requested_topping)

输出结果

TrueFalse

5.2.7 检查特定值是否不包含在列表中

确定特定的值未包含在列表中,使用关键字not in

banned_users = ['andrew','carolina','david']user = 'marie'if user not in banned_users:#如果user 的值未包含在列表banned_users 中,Python将返回True ,进而执行缩进的代码行。 print(user.title() + ",you canpost a response if you want.")

用户’marie’ 未包含在列表banned_users 中,因此她将看到一条邀请她发表评论的消息

输出结果

Marie, you can post a response if you wish.

5.2.8 布尔表达式game_active = Trueprint(game_active)can_edit = Falseprint(can_edit)

5.3.1 简单的if语句age = 19if age > 18: print("You are old enough to vote!")

5.3.2 if-else语句

在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作,使用if-else语句

age = 17if age >= 18: print("You are old enough to vote!") print("Have you registered to vote yet?")else: print("Sorry, you are too young to vote!") print("Please refuster to vote a soon as you turn 18!")

执行结果

Sorry, you are too young to vote.

Please register to vote as soon as you turn 18!

5.3.3 if-elif-else语句

检查超过两个的情形,只执行if-elif-slse结构中的一个代码块,依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,将执行紧跟其后的代码,并跳过余下的测试

eg:一个根据年龄段收费的游乐场

4岁以下免费 4~18收5块 18(含)以上收10块 age = 12if age


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3