一、Python系统关键字
关键字 | 作用 |
---|---|
and | 逻辑与 |
or | 逻辑或 |
not | 逻辑非 |
if | 条件语句,常与else、elif结合使用 |
elif | 条件语句,常与if、else结合使用 |
else | 在条件语句中使用,与if、elif结合使用。也可用于异常和循环语句 |
for | for循环语句 |
while | while循环语句 |
True | 布尔类型的值,表示真,与False相反 |
False | 布尔类型的值,表示假,与True相反 |
continue | 跳出本次循环,断续执行下一次循环 |
break | 中断整个循环语句的执行 |
pass | 空的类、方法或函数的占位符 |
try | 常用于捕捉异常,与except、finally 结合使用 |
except | except 包含捕获异常后的操作代码块,与try、finally 结合使用 |
finally | 出现异常后,始终要执行finally 包含的代码块,与try、except 结合使用。 |
raise | 抛出异常 |
from | 用于导入模块,与import 结合使用 |
import | 用于导入模块,与from结合使用 |
def | 定义函数或方法 |
return | 函数或方法的返回值 |
class | 定义一个类 |
lambda | 匿名函数 |
del | 删除变量或某个序列中的值 |
global | 定义一个全局变量 |
nonlocal | 声明一个非局部变量,用于标识外部作用域的变量 |
in | 判断某个变量是否在序列中 |
is | 判断是否是同一个对象 |
None | 表示什么也没有,它有自己的数据类型- NoneType |
assert | 用于调试 |
as | 创建别名 |
with | 常和open使用,用于读取或写入文件 |
yield | 结束一个函数,返回一个生成器,用于从函数依次返回值 |
二、13个Python必备的知识
2.1 数据类型
数据类型是可以存储在变量中的数据规范。解释器根据变量的类型为变量分配内存。
2.2 变量
变量是存放数据值的容器。
变量可以使用短名称(如x和y)或更具描述性的名称(age、carname、total_volume)。
Python 变量命名规则:
● 变量名必须以字母或下划线字符开头
● 变量名称不能以数字开头
● 变量名只能包含字母数字字符和下划线(A-z、0-9和_)
● 变量名称区分大小写(age、Age和AGE是三个不同的变量)
x = 10
y = "Bill"
print(x)
print(y)
2.3 列表(List)
列表(List)是一种有序和可更改的集合,允许重复的成员。
它可能不是同质的,可以创建一个包含不同数据类型(如整数、字符串和对象)的列表。
companies = ["apple","google","tcs","accenture"]
print(companies)
print(len(companies))
#['apple', 'google', 'tcs', 'accenture']
#4
companies.append("infosys")
print(companies)
print(len(companies))
#['apple', 'google', 'tcs', 'accenture', 'infosys']
#5
print(companies[2])
print(companies[-2])
print(companies[1:])
print(companies[:1])
print(companies[1:3])
#tcs
#accenture
#['google', 'tcs', 'accenture', 'infosys']
#['apple']
#['google', 'tcs']
companies.remove("infosys")
print(companies)
#['apple', 'google', 'tcs', 'accenture']
companies.pop()
print(companies)
#['apple', 'google', 'tcs']
2.4 集合(set)
集合(Set)是一个无序和无索引的集合,没有重复的成员。
对于从列表中删除重复条目非常有用。它还支持各种数学运算,例如并集、交集和差分。
thisset = {"apple", "banana", "cherry"}
print(thisset)
#{'banana', 'cherry', 'apple'}
- 添加项目
- 要将一个项添加到集合,请使用 add() 方法。
- 要向集合中添加多个项目,请使用 update() 方法。
>>> thisset = {"apple", "banana", "cherry"}
>>>
>>> thisset.add("orange")
>>> print(thisset)
#{'cherry', 'banana', 'apple', 'orange'}
>>>
>>> thisset.update(["orange", "mango", "grapes"])
>>> print(thisset)
#{'apple', 'banana', 'orange', 'grapes', 'mango', 'cherry'}
- 集合的内建方法
方法 | 描述 |
---|---|
add() | 向集合添加元素。 |
clear() | 删除集合中的所有元素。 |
copy() | 返回集合的副本。 |
difference() | 返回包含两个或更多集合之间差异的集合。 |
difference_update() | 删除此集合中也包含在另一个指定集合中的项目。 |
discard() | 删除指定项目。 |
intersection() | 返回为两个其他集合的交集的集合。 |
intersection_update() | 删除此集合中不存在于其他指定集合中的项目。 |
isdisjoint() | 返回两个集合是否有交集。 |
issubset() | 返回另一个集合是否包含此集合。 |
issuperset() | 返回此集合是否包含另一个集合。 |
pop() | 从集合中删除一个元素。 |
remove() | 删除指定元素。 |
symmetric_difference() | 返回具有两组集合的对称差集的集合。 |
symmetric_difference_update() | 插入此集合和另一个集合的对称差集。 |
union() | 返回包含集合并集的集合。 |
update() | 用此集合和其他集合的并集来更新集合。 |
2.5 字典(Dictionary)
字典是作为键值对的可变无序项集合。
与其他数据类型不同,它以**【键:值】**对格式保存数据,而不是存储单个数据。此功能使其成为映射JSON响应的最佳数据结构。
# example 1
user = { 'username': 'Fan', 'age': 20, 'mail_id': 'codemaker2022@qq.com', 'phone': '18650886088' }
print(user)
#{'username': 'Fan', 'age': 20, 'mail_id': 'codemaker2022@qq.com', 'phone': '18650886088'}
print(user['age'])
#20
for key in user.keys():
print(key)
"""
username
age
mail_id
phone
"""
for value in user.values():
print(value)
"""
Fan
20
codemaker2022@qq.com
18650886088
"""
for item in user.items():
print(item)
"""
('username', 'Fan')
('age', 20)
('mail_id', 'codemaker2022@qq.com')
('phone', '18650886088')
"""
# example 2
user = {
'username': "Fan",
'social_media': [
{
'name': "Linkedin",
'url': "https://www.linkedin.com/in/codemaker2022"
},
{
'name': "Github",
'url': "https://github.com/codemaker2022"
},
{
'name': "QQ",
'url': "https://codemaker2022.qq.com"
}
],
'contact': [
{
'mail': [
"mail.Fan@sina.com",
"codemaker2022@qq.com"
],
'phone': "18650886088"
}
]
}
print(user)
print(user['social_media'][0]['url'])
print(user['contact'])
#{'username': 'Fan', 'contact': [{'mail': ['mail.Fan@sina.com', 'codemaker2022@qq.com'], 'phone': '18650886088'}], 'social_media': [{'url': 'https://www.linkedin.com/in/codemaker2022', 'name': 'Linkedin'}, {'url': 'https://github.com/codemaker2022', 'name': 'Github'}, {'url': 'https://codemaker2022.qq.com', 'name': 'QQ'}]}
#https://www.linkedin.com/in/codemaker2022
#[{'mail': ['mail.Fan@sina.com', 'codemaker2022@qq.com'], 'phone': '18650886088'}]
2.6 注释
单行注释,以井字符 #
开头,后面带有消息并在行尾结束。
#This is a comment
#written in
#more than just one line
print("Hello, World!")
#Hello, World!
多行注释,用特殊引号"""
括起来,可以将消息放在多行中。
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
#Hello, World!
2.7 基本功能
print()
函数在控制台中打印提供的消息。此外还可以提供文件或缓冲区输入作为在屏幕上打印的参数。
input()
函数用于收集来自控制台的用户输入 。
>>> name = input("Enter your name: ")
Enter your name: carry
>>> print("Hello", name)
Hello carry
这里需要注意,
input()
会把输入的任何内容转换为字符串。
因此,如果将年龄作为整数值提供,但input()
方法将其作为字符串返回,此时就需要手动将其转换为整数。
len()
可以查看对象的长度。如果输入一个字符串,则可以获取指定字符串中的字符数。
>>> str1 = "Hello World"
>>> print("The length of the string is ", len(str1))
The length of the string is 11
str()
用于将其他数据类型转换为字符串值。
int()
用于将字符串转换为整数。
2.8 条件语句
条件语句是用于根据特定条件更改程序流程的代码块。这些语句只有在满足特定条件时才会执行。
- Python 条件
- 等于:a == b
- 不等于:a != b
- 小于:a < b
- 小于等于:a <= b
- 大于:a > b
- 大于等于:a >= b
在Python中,使用if,if-else,循环(for,while)作为条件语句根据某些条件来改变程序的流程。
- if-else语句
1.1 else 关键字捕获未被之前的条件捕获的任何内容。
a = 200
b = 66
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
#b is not greater than a
1.2 如果只有一条语句要执行,则可以将其与 if 语句放在同一行。
a = 200
b = 66
if a > b: print("a is greater than b")
#a is greater than b
还可以在同一行上使用多个 else 语句:
>>> a = 200
>>> b = 66
>>> print("A") if a > b else print("B")
A
>>> print("A") if a > b else print("=") if a == b else print("B")
A
- elif语句
elif
关键字是 python 对“如果之前的条件不正确,则试试这个条件”的表达方式。
a = 66
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
#a and b are equal
2.9 循环语句
循环是一个条件语句,用于重复某些语句(在其主体中),直到满足某个条件。
Python 有两个原始的循环命令:
while
循环for
循环
1. for循环
for
循环用于迭代序列(即列表,元组,字典,集合或字符串)。
for x in "banana":
print(x)
#apple
#banana
#cherry
break 语句
通过使用 break 语句,我们可以在循环遍历所有项目之前停止循环:
- 如果 x 是 “banana”,则退出循环:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
- 当 x 为 “banana” 时退出循环,但这次在打印之前中断:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
continue 语句
通过使用 continue 语句,我们可以停止循环的当前迭代,并继续下一个:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
range() 函数
如需循环一组代码指定的次数,我们可以使用 range()
函数。
range(end) 或 range(start,end[,step])
参数说明:
- start:计数从start开始,默认是从0开始
- stop:计数到stop结束,但是不包括stop
- step:步长,默认为1
range()
函数返回一个数字序列,默认情况下从 0 开始,并递增 1(默认地),并以指定的数字结束。
- For 循环中的 Else
for 循环中的 else 关键字指定循环结束时要执行的代码块。
实例:打印 0 到 9 的所有数字,并在循环结束时打印一条消息
for x in range(10):
print(x)
else:
print("Finally finished!")
- 嵌套循环
嵌套循环是循环内的循环。即“外循环”每迭代一次,“内循环”将执行一次。
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
2.while 循环
使用 while 循环,只要条件为真,就可以执行一组语句。
可以在while循环的末尾使用else,类似于for循环,当条件为假时执行一些语句。
>>> count = 0
>>> while (count < 5):
>>> print(count)
>>> count = count + 1
>>> else:
>>> print("Count is greater than 4")
0
1
2
3
4
Count is greater than 4
2.10 函数
函数是一种仅在调用时运行的代码块。在代码中实现模块化并使代码可重用,这是非常有用的。
2.11 处理异常
即使语句在语法上是正确的,它也可能在执行时发生错误。这些类型的错误称为异常。可以使用异常处理机制来避免此类问题。
在Python中,使用try...except
和 finally
关键字在代码中实现异常处理。
try
块允许您测试代码块以查找错误。except
块允许您处理错误。finally
块允许您执行代码,无论 try 和 except 块的结果如何。
2.12 字符串操作
字符串是用单引号或双引号(',")括起来的字符集合。
可以使用内置方法对字符串执行各种操作,如连接、切片、修剪、反转、大小写更改和格式化,如split()
、lower()
、upper()
、endswith()
、join()
和ljust()
、rjust()
、format()
。详细了解可参见《python字符串》。
2.13 正则表达式
● 导入regex模块,import re
。
● re.compile()
使用该函数创建一个Regex对象。
● 将搜索字符串传递给search()
方法。
● 调用group()
方法返回匹配的文本。