- 备注
"""
单行备注
#备注消息
多行备注
三个双引号之间
"""
备注信息
"""
- Python 变量命名规则:
字符串变量可使用单引号或双引号进行声明
变量名以字母或下划线字符开头,不能以数字开头
变量名只能包含字母数字字符和下划线
区分大小写
- 多个变量赋值
Python在一行中为多个变量分配相同的值:
x, y, z = "A", "B", "C"
print(x)
print(y)
print(z)
- 输出变量
print 语句常用于输出变量。
结合文本和变量, + 字符:
字符串和数字不能相结合
- 全局变量和局部变量
局部变量就是定义在一个函数体内部的变量
全局变量是定义在外面的变量
如果在函数内部创建具有相同名称的变量,则该变量将是局部变量,并且只能在函数内部使用。
global 关键字
函数内部创建全局变量,使用 global 关键字。
def f():
global x
x = "LIHUA"
f()
print("Python is " + x)
函数内部更改全局变量的值, global 关键字引用该变量:
x = "XIAO"
def F():
global x
x = "LIHUAc"
F()
print("my name is " + x)
- 基础方法
type()获取任何对象的数据类型
len() 函数获取字符串的长度。
strip() 方法删除开头和结尾的空白字符
a = " Hello "
print(a.strip())
lower() 返回小写的字符串:
a = "Hello"
print(a.lower())
upper() 方法返回大写的字符串:
a = "Hello"
print(a.upper())
replace() 用另一段字符串来替换字符串:
a = "Hello!"
print(a.replace("World"))
split() 方法在找到分隔符的实例时将字符串拆分为子字符串:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
是否存在:
text = "my name is lihua"
x = "is" in text
print(x)
是否没有:
text = "my name is lihua"
x = "is" not in text
print(x)
format() 方法组合字符串和数字
er = 3
sf = 567
gr = 49.95
my = "I want to pay {2} dollars for {0} pieces of item {1}."
print(my.format(er, gr, sf))
- True and False(布尔)
除空字符串外,任何字符串均为 True。
除 0 外,任何数字均为 True。
除空列表外,任何列表、元组、集合和字典均为 True。
除空值(例如 ()、[]、{}、""、数字 0 和值 None)外,没有多少值会被评估为 False。值 False 的计算结果为 False。
返回 False:None,0,"",(),[],{}
函数返回布尔
Python 还有很多返回布尔值的内置函数,例如 isinstance() 函数,该函数可用于确定对象是否具有某种数据类型:
检查对象是否是整数:
x = 200
print(isinstance(x, int))
- 字符串(基本)
通过使用变量名称后跟等号和字符串,可以把字符串赋值给变量:
可使用三个引号将多行字符串赋值给变量:
字符串是数组
没有字符数据类型,单个字符就是长度为 1 的字符串。
方括号可用于访问字符串的元素
- 裁切语法(正负)
您可以使用裁切语法返回一定范围的字符。
指定开始索引和结束索引,以冒号分隔,以返回字符串的一部分。
获取从位置 2 到位置 5(不包括)的字符:
b = "Hello!"
print(b[2:5])
负的索引
负索引表示从末尾开始,-1 表示最后一个项目,-2 表示倒数第二个项目
b = "Hello,World!"
print(b[-5:-2])
- Python 四种集合数据类型:
列表(List)是一种有序和可更改的集合。允许重复的成员。
元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。
集合(Set)是一个无序和无索引的集合。没有重复的成员。
词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员。
- 列表是一个有序且可更改的集合。在 Python 中,列表用方括号编写。
最后一项
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
索引范围
返回值将是包含指定项目的新列表
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
搜索将从索引 2(包括)开始,到索引 5(不包括)结束。
如果要从列表末尾开始搜索,负索引:
返回从索引 -4(包括)到索引 -1(排除)的项目:
t = ["a", "b", "c", "d", "e", "f", "g"]
print(t[-4:-1])
遍历列表,for 循环遍历列表项
引用索引号更改特定项目的值:
t = ["apple", "banana", "cherry"]
t[1] = "bear"
print(t)
检查项目是否存在使用 in 关键字
如需确定列表中有多少项,请使用 len() 方法:
t = ["apple", "banana", "cherry"]
print(len(t))
添加项目
添加到列表的末尾,请使用 append() 方法:
使用 append() 方法追加项目:
t = ["apple", "banana", "cherry"]
t.append("orange")
print(thislist)
使用 insert() 方法在指定的索引处添:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
删除项目
remove() 方法删除指定的项目:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
pop() 方法删除指定的索引(如果未指定索引,则删除最后一项)
del 关键字删除指定的索引:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
del 关键字能完整地删除列表
clear() 方法清空列表:
复制列表
使用 copy() 方法来复制列表:
t = ["apple", "banana", "cherry"]
mylist = t.copy()
print(mylist)
使用 list() 方法复制列表:
t = ["apple", "banana", "cherry"]
mylist = list(t)
print(mylist)
合并两个列表
使用 + 运算符。
l1 = ["a", "b" , "c"]
l2 = [1, 2, 3]
l3 = l1 + l2
print(l3)
把 list2 追加到 list1 中:
l1 = ["a", "b" , "c"]
l2 = [1, 2, 3]
for x in l2:
l1.append(x)
print(l1)
extend() 方法将 list2 添加到 list1 的末尾:
l1 = ["a", "b" , "c"]
l2 = [1, 2, 3]
l1.extend(l2)
print(l1)
运行实例
list() 构造函数
创建列表:
thislist = list(("apple", "banana", "cherry")) # 双括号
print(thislist)
- 元组(Tuple)
元组是有序且不可更改的集合。元组是用圆括号编写。
创建元组:
this = ("apple", "banana", "cherry")
print(this)
访问元组项目
方括号内的索引号来访问元组项目:
索引范围
三、四、5项目:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
2(包括)开始, 5(不包括)结束
负索引从元组的末尾开始搜索引 -4(包括)到索引 -1(排除)的项目:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
更改元组值
元组是不可变的,可以将元组转换为列表,更改列表,然后将列表转换回元组。
把元组转换为列表即可进行更改:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
遍历元组
使用 for 循环遍历元组项目。
检查项目是否存在
要确定元组中是否存在指定的项,请使用 in 关键字:
元组长度
要确定元组有多少项,请使用 len() 方法:
添加项目
元组一旦创建无法向其添加项目
创建有一个项目的元组
仅包含一个项目的元组,必须在该项目后添加一个逗号,否则 Python 无法将变量识别为元组。
删除项目
无法删除元组中的项目。
元组是不可更改的,不可以删除某个项目,但可以完全删除元组:
del 关键字可以完全删除元组:
合并两个元组
使用 + 运算符:
tuple() 构造函数,来创建元组。
this = tuple(("apple", "banana", "cherry")) # 双括号
print(this)
元组方法
count() 返回元组中指定值出现的次数。
index() 在元组中搜索指定的值并返回它被找到的位置。
- 集合(Set)
集合是无序和无索引的集合。用花括号编写。
创建集合:
thisset = {"apple", "banana", "cherry"}
print(thisset)
访问项目
使用 for 循环遍历 set 项目,或使用 in 关键字查询集合中是否存在指定值。
遍历集合,并打印值:
sset = {"apple", "banana", "cherry"}
for x in sset:
print(x)
检查 set 中是否存在 “banana”:
isset = {"apple", "banana", "cherry"}
print("banana" in isset)
更改项目
集合一旦创建,无法更改项目,可添加新项目。
要将一个项添加到集合,请使用 add() 方法。
要向集合中添加多个项目,请使用 update() 方法。
使用 add() 方法向 set 添加项目:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
获取 Set 的长度
要确定集合中有多少项,请使用 len() 方法。
t= {"a", "b", "c"}
print(len(t))
删除项目
使用 remove() 或 discard() 方法。
t = {"apple", "banana", "cherry"}
t.remove("banana")
print(t)
注释:如果要删除的项目不存在将引发错误。
tt = {"apple", "banana", "cherry"}
t.discard("banana")
print(t)
如果要删除的项目不存在 discard() 不会引发错误。
您还可以使用 pop() 方法删除项目,但此方法将删除最后一项。set 是无序的,不会知道被删除的是什么项目。返回值是被删除的项目。
t = {"apple", "banana", "cherry"}
x = t.pop()
print(x)
print(t)
clear() 方法清空集合:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
del 彻底删除集合:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
合并两个集合
连接两个或多个集合。
union() 方法返回包含两个集合中所有项目的新集合
update() 方法将一个集合中的所有项目插入另一个集合中
t1 = {"a", "b" , "c"}
t2 = {1, 2, 3}
t3 = t1.union(t2)
print(t3)
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
union() 和 update() 都将排除任何重复项。
set() 构造函数
t = set(("apple", "banana", "cherry")) # 请留意这个双括号
print(t)
Set 方法
add() 向集合添加元素。
clear() 删除集合中的所有元素。
copy() 返回集合的副本。
difference() 返回包含两个或更多集合之间差异的集合。
difference_update() 删除此集合中也包含在另一个指定集合中的项目。
discard() 删除指定项目。
intersection() 返回为两个其他集合的交集的集合。
intersection_update() 删除此集合中不存在于其他指定集合中的项目。
isdisjoint() 返回两个集合是否有交集。
issubset() 返回另一个集合是否包含此集合。
issuperset() 返回此集合是否包含另一个集合。
pop() 从集合中删除一个元素。
remove() 删除指定元素。
symmetric_difference() 返回具有两组集合的对称差集的集合。
symmetric_difference_update() 插入此集合和另一个集合的对称差集。
union() 返回包含集合并集的集合。
update() 用此集合和其他集合的并集来更新集合。
- 字典(Dictionary)
字典是一个无序、可变和有索引的集合。用花括号编写,拥有键和值。
t = {
"A": "Poe",
"B": "91",
"C": "22"
}
print(t)
访问项目,方括号内引用其键名来访问字典的项目:
获取 "model" 键的值:
x = thisdict["model"]
get() 的方法相同的结果:
获取 "model" 键的值:
x = thisdict.get("model")
更改值
引用其键名来更改特定项的值:
thisdict = {
"A": "he",
"B": "91",
"C": 19
}
thisdict["C"] = 20
遍历字典, for 循环遍历字典。
逐个打印字典中的所有键名:
for x in thisdict:
print(x)
逐个打印字典中的所有值:
for x in thisdict:
print(thisdict[x])
values() 函数返回字典的值:
for x in thisdict.values():
print(x)
items() 函数遍历键和值:
for x, y in thisdict.items():
print(x, y)
检查键是否存在
要确定字典中是否存在BY in 关键字:
thisdict = {
"A": "he",
"B": "11",
"C": 19
}
if "B" in thisdict:
print("Yes")
字典长度
要确定字典有多少项目(键值对),请使用 len() 方法。
打印字典中的项目数:
print(len(thisdict))
添加项目
使用新的索引键并为其赋值,将项目添加到字典中:
thisdict["color"] = "red"
print(thisdict)
删除项目
pop() 方法删除具有指定键名的项:
thisdict.pop(B")
print(thisdict)
popitem() 方法删除最后插入的项目(在 3.7 之前的版本中,删除随机项目):
thisdict.popitem()
print(thisdict)
del 关键字删除具有指定键名的项目:
del thisdict["model"]
print(thisdict)
del 关键字也可以完全删除字典:
del thisdict
print(thisdict) #this 会导致错误,因为 "thisdict" 不再存在。
clear() 关键字清空字典:
thisdict.clear()
print(thisdict)
复制字典
不能通过键入 dict2 = dict1 来复制字典,因为dict2 只是对 dict1 的引用,而 dict1 中的更改也将自动在 dict2 中进行。
copy() 方法来复制字典:
mydict = thisdict.copy()
print(mydict)
dict() 方法创建字典的副本:
mydict = dict(thisdict)
print(mydict)
嵌套字典,可以包含许多词典
创建包含三个字典的字典:
myfamily = {
"child1" : {
"name" : "XIOAMING",
"year" : 2003
},
"child2" : {
"name" : "LIHUA",
"year" :2004
},
"child3" : {
"name" : "CONGCONG",
"year" : 2005
}
}
创建三个字典,然后创建一个包含其他三个字典的字典:
同上
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
dict() 构造函数创建新的字典:
t = dict(i="P", m="9", r=13)
print(t)
字典方法
clear() 删除字典中的所有元素
copy() 返回字典的副本
fromkeys() 返回拥有指定键和值的字典
get() 返回指定键的值
items() 返回包含每个键值对的元组的列表
keys() 返回包含字典键的列表
pop() 删除拥有指定键的元素
popitem() 删除最后插入的键值对
setdefault() 返回指定键的值。如果该键不存在,则插入具有指定值的键。
update() 使用指定的键值对字典进行更新
values() 返回字典中所有值的列表
- Python If Else
a == b,a != b,a < b,a <= b
a = 66
b = 200
if b > a:
print("b is greater than a")
缩进
没有缩进的 If 语句会引发错误
elif 关键字
a = 66
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else 关键字,以上不满足
a = 200
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
没有 elif 的 else:
a = 200
b = 66
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
简写 If,一条语句要执行,则可以将其与 if 语句放在同一行。
a = 200
b = 66
if a > b: print("a is greater than b")
简写 If ... Else
如果只有两条语句要执行,一条用于 if,另一条用于 else,放在同一行:
print("A") if a > b else print("B")
您还可以在同一行上使用多个 else 语句:
单行 if else 语句,有三个条件:
a = 200
b = 66
print("A") if a > b else print("=") if a == b else print("B")
And
a 是否大于 b且 c 是否大于 a:
a = 200
b = 66
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
a 是否大于 b或者 a 是否大于 c:
a = 200
b = 66
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
嵌套 If
x = 52
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
pass 语句
if 语句不能为空,无内容的 if 语句用 pass 语句来避免错误。
a = 66
b = 200
if b > a:
pass
range() 函数
for x in range(10):
print(x)
注意:range(10) 0 到 9。
r:range(3, 10) 3 到 10(但不包括 10):
range() 函数默认将序列递增 1,可通过添加第三个参数来指定增量值:range(2, 30, 3)
for x in range(3, 50, 6):
print(x)
默认参数值
如果调用了不带参数的函数,则使用默认值:
def my_function(country = "China"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
以 List 传参
发送到函数的参数可以是任何数据类型(字符串、数字、列表、字典等),并且在函数内其将被视为相同数据类型。
将 List 作为参数发送,它到达函数时仍将是 List(列表):
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
返回值
如需使函数返回值,请使用 return 语句:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
关键字参数
可使用 key = value 语法发送参数。参数的顺序无关紧要。
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")
“关键字参数”一词通常简称为 kwargs。
任意参数
不知道将传递给您的函数多少个参数,在函数定义的参数名称前添加 *。
函数将接收一个参数元组,并可以相应地访问各项:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Phoebe", "Jennifer", "Rory")
- 文件
Python 文件打开
使用内建的 open() 函数。
open() 函数返回文件对象,此对象有一个 read() 方法用于读取文件的内容:
f = open("demofile.txt", "r")
print(f.read())
读取文件的一部分
默认情况下,read() 方法返回整个文本,但也可以指定要返回的字符数:
f = open("demofile.txt", "r")
print(f.read(5))
您可以使用 readline() 方法返回一行:
f = open("demofile.txt", "r")
print(f.readline())
通过两次调用 readline(),读取前两行:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
通过循环遍历文件中的行,您可以逐行读取整个文件:
f = open("demofile.txt", "r")
for x in f:
print(x)
关闭文件
完成后始终关闭文件
f = open("demofile.txt", "r")
print(f.readline())
f.close()
由于反斜杠在Python中被视为转义标记,为在Windows中确保万无一失,应以原始字符串的方式指定路径,即在开头的单引号前加上r。
文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的。
写入已有文件
如需写入已有的文件,向 open() 函数添加参数:
"a" - 追加 - 会追加到文件的末尾
"w" - 写入 - 会覆盖任何已有的内容
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
追加后,打开并读取该文件:
f = open("demofile2.txt", "r")
print(f.read())
打开文件 "demofile3.txt" 并覆盖内容:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
写入后,打开并读取该文件:
f = open("demofile3.txt", "r")
print(f.read())
"w" 方法会覆盖全部内容。
创建新文件,用 open() 方法,并用以下参数之一:
"x" - 创建 - 将创建一个文件,如果文件存在则返回错误
"a" - 追加 - 如果指定的文件不存在,将创建一个文件
"w" - 写入 - 如果指定的文件不存在,将创建一个文件
创建名为 "myfile.txt" 的文件:
f = open("myfile.txt", "x")
如果不存在,则创建新文件:
f = open("myfile.txt", "w")
Python 删除文件
如需删除文件,必须导入 OS 模块,并运行其 os.remove() 函数:
删除文件 "demofile.txt":
import os
os.remove("demofile.txt")
检查文件是否存在
为避免出现错误,需要在尝试删除文件之前检查该文件是否存在:
检查文件是否存在,然后删除它:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
删除文件
os.rmdir() 方法删除整个文件夹(只能删除空文件夹):
删除文件夹 "fold":
import os
os.rmdir("fold")