1数据类型和变量
内置数据类型
- 字符串:字符序列,通过将字符括在引号中来定义。
name = "Ebi"
- 整数:整数,包括正数和负数。
age = 34
- 浮点数:包含小数点的数字。
height = 187
- 布尔值:表示真值,True 或 False。
is_student = False
类型转换
- 类型之间转换:说明如何使用 int()、float() 和 str() 等函数在数据类型之间进行转换。
price = "19.9" # String
price_float = float(price) # Convert to float
2 Python 中的运算符
Python 中的运算符是促进对数据类型进行各种操作的重要组件。本节详细概述了五类运算符:算术运算符、赋值运算符、比较运算符、隶属关系运算符和逻辑运算符,并附有 Python 中的说明性示例。
2.1 算术运算符
算术运算符对数值执行基本数学运算。在 Python 中,常见的算术运算符包括:
- 加法 (+):将两个数字相加。
a = 10
b = 5
result = a + b # result is 15
- Subtract (-):从第一个操作数中减去第二个操作数。
result = a - b # result is 5
- 乘法 (*):将两个数字相乘。
result = a * b # result is 50
- 除法 (/):将分子除以分母(返回浮点数)。
result = a / b # result is 2.0
- 向下取整除法 ():除以并返回小于或等于结果的最大整数。
result = a // b # result is 2
- 模数 (%):返回除法的余数。
result = a % b # result is 0
- 幂 (**):将一个数字提高到另一个数字的幂。
result = a ** 2 # result is 100
2.2 赋值运算符
赋值运算符为变量赋值。基本赋值运算符是等号 (=),但 Python 还包括复合赋值运算符:
- 简单赋值 (=):
x = 10
- 添加和分配 (+=):
x += 5 # x is now 15
- 减去和赋值 (-=):
x -= 3 # x is now 12
- 乘法和赋值 (*=):
x *= 2 # x is now 24
- 划分和分配 (/=):
x /= 4 # x is now 6.0
2.3 比较运算符
比较运算符比较两个值并返回布尔结果(True 或 False)。Python 中常见的比较运算符是:
- 等于 (==):
is_equal = (a == b) # is_equal is False
- 不等于 (!=):
not_equal = (a != b) # not_equal is True
- 大于 (>):
is_greater = (a > b) # is_greater is True
- 小于 (<):
is_less = (a < b) # is_less is False
- 大于或等于 (>=):
is_greater_equal = (a >= b) # is_greater_equal is True
- 小于或等于 (<=):
is_less_equal = (a <= b) # is_less_equal is False
2.4 成员资格运算符
成员身份运算符确定集合中是否存在值(如列表、元组或字符串)。主要成员资格运算符是:
- 在 (in):
my_list = [1, 2, 3, 4, 5]
exists = 3 in my_list # exists is True
- 不在 (not in):
exists = 6 not in my_list # exists is True
2.5 逻辑运算符
逻辑运算符用于组合多个布尔表达式。Python 中的主要逻辑运算符包括:
- And (and):如果两个表达式都为 true,则返回 True。
a = 10
b = 5
condition = (a > 5 and b < 10) # condition is True
- Or (or):如果至少有一个表达式为 true,则返回 True。
condition = (a < 5 or b < 10) # condition is True
- Not (not):反转表达式的布尔值。
condition = not (a > b) # condition is True
3 Python 中的控制结构:条件语句(if、elif、else)
控制结构是编程的基本组成部分,允许在程序中进行决策过程。在 Python 中,if、elif 和 else 等条件语句根据指定条件指导执行流程。本节提供了这些控制结构的专业概述,并附有实际示例。
3.1 if语句
if 语句计算条件,并仅在该条件为 True 时执行代码块。这允许根据动态条件执行不同的代码路径。
例:
age = 18
if age >= 18:
print("You are eligible to vote.")
输出:
You are eligible to vote.
3.2 elif语句
elif(“else if”的缩写)语句允许按顺序测试多个条件。如果 if 语句的条件为 False,则评估 elif 语句。对于各种条件,您可以有多个 elif 语句。
例:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
输出:
Grade: B
3.3 else语句
else 语句是一个可选的 final 块,如果前面的所有条件(if 和 elif)都是 False,则执行该块。它为先前条件未专门处理的任何情况提供 catch-all。
例:
temperature = 30
if temperature > 30:
print("It's hot outside.")
elif temperature < 20:
print("It's cold outside.")
else:
print("The weather is moderate.")
输出:
The weather is moderate.
3.4 组合条件
还可以使用逻辑运算符 (and、or、not) 组合多个条件。这允许在 control flow 中使用更复杂的 branching logic。
例:
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("You can relax today!")
else:
print("Time to get to work.")
输出:
You can relax today!
3.5 嵌套条件语句
条件语句可以相互嵌套,从而允许更精细的决策。
例:
num = 20
if num > 0:
print("The number is positive.")
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
else:
print("The number is negative.")
输出:
The number is positive.
The number is even.
4 Python 中的循环:循环构造 (for,while)
循环是编程中强大的控制结构,可促进多次执行代码块,从而允许对序列、集合进行高效迭代,或者直到满足特定条件。在 Python 中,循环的两种主要类型是 for 循环和 while 循环。本节探讨了这些循环结构,并为每个结构提供了示例和使用案例。
4.1 for循环
- Python 中的 for 循环用于迭代序列(例如列表、元组、字典、字符串或范围)。
- 它允许您为序列中的每个项目执行一个代码块。
- for 循环的主要目的是对可迭代对象中的每个元素执行操作。
- 循环用于重复执行代码块固定次数,或者直到满足特定条件,只要某些条件为 true。
语法:
for variable in iterable:
# Code to execute for each item
何时使用for循环
1. 迭代序列:
- 用例:当您知道确切的迭代次数或需要迭代集合中的元素(如列表、元组、字符串或范围)时。
- 示例:遍历项目列表,如前所述。?
courses = ["machine learning", "python", "NLP"]
for course in courses:
print(course)
输出:
machine learning
python
NLP
2. 使用范围:
- 用例:当您想将代码块重复一定次数时。
- 示例:使用 range() 函数执行特定迭代次数的循环。可以在 for 循环中使用 range() 函数来重复一个动作指定次数。
for i in range(5):
print(f"Iteration {i + 1}")
输出:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
3. 使用 Index 迭代:
- 用例:如果您同时需要集合中元素的索引和值。
- 示例:使用 enumerate() 函数。
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"Color {index}: {color}")
输出:
Color 0: red
Color 1: green
Color 2: blue
4.2while循环
- 只要指定的条件为 true,Python 中的 while 循环就会重复执行一段代码。
- 当您事先不知道迭代次数并希望继续直到特定条件发生变化时,这种类型的循环非常有用。
语法:
while condition:
# Block of code to be executed
- condition:这是一个布尔表达式,在循环的每次迭代之前进行计算。如果计算结果为 True,则将执行循环;如果计算结果为 False,则循环将终止。
- 代码块:这是缩进代码块,只要条件为 True,它就会在每次迭代时运行。
示例:基本 while 循环
count = 0
while count < 5:
print(f"Count is {count}.")
count += 1 # Increment count to avoid infinite loop
输出:
Count is 0.
Count is 1.
Count is 2.
Count is 3.
Count is 4.
何时使用 while 循环
- 未知的迭代次数:
- 用例:当事先不知道迭代次数,并且您希望继续循环直到满足特定条件时。
- 示例:持续接受用户输入,直到满足特定条件。
user_input = ""
while user_input != "exit":
user_input = input("Type 'exit' to stop: ")
2. 基于条件的循环:
- 用例: 当您检查在循环期间可能会更改的条件并希望保持循环直到该条件不再有效时。
- 示例:使用 while 循环实现倒计时。
import time
count = 3
while count > 0:
print(count)
count -= 1
time.sleep(1)
print("Go!")
输出:
3
2
1
Go!
3. 事件驱动的循环:
- 使用案例:在您等待事件或状态更改的情况下,例如检查设备状态、轮询 API 等。
is_ready = False
while not is_ready:
print("Waiting for the system to be ready...")
# code to check if the system is ready
# is_ready = check_system_status()
break
print("System is ready!")
输出:
Waiting for the system to be ready...
System is ready!
总结:
在以下情况下使用 for 循环:
- 您知道要迭代多少次(尤其是对于集合)。
- 您希望轻松访问集合中的每个元素。
在以下情况下使用 while 循环:
- 迭代次数未知,取决于某些条件。
- 您正在等待特定条件变为 false。
4.3 控制循环执行
Python 提供了几个语句来控制循环的流程:
break:立即退出循环,无论条件如何。
- 示例:跳出循环
for number in range(10):
if number == 5:
break
print(number)
输出:
0
1
2
3
4
continue:跳过当前迭代并继续循环的下一次迭代。
- 示例:使用 continue
for number in range(5):
if number == 2:
continue # Skip number 2
print(number)
输出:
0
1
3
4
4.4 嵌套 Loop
Loop 可以嵌套,这意味着您可以将一个 Loop 放在另一个 Loop 中。这对于迭代多维结构很有用。
示例:嵌套循环
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")
输出:
i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
5 Python 中for循环的几种高级形式
1. 带有zip()函数的 For 循环
zip() 函数允许您并行迭代两个或多个可迭代对象(如列表或元组)。
- 例:
names = ["Ebi", "Ela", "Alex"]
ages = [34, 30, 51]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
输出:
Ebi is 34 years old.
Ela is 30 years old.
Alex is 51 years old.
2. 带有enumerate()函数的 For 循环
enumerate() 函数向可迭代对象添加一个计数器,同时返回元素的索引和值。
- 示例:
cars = ["BMW", "Honda", "Cadillac"]
for index, car in enumerate(cars):
print(f"{index}: {car}")
输出:
0: BMW
1: Honda
2: Cadillac
3. 带字典的 For 循环
您可以遍历字典以访问其键和/或值。
- 例:
student = {"name": "Ebi", "age": 34, "major": "Computer Science"}
for k, v in student.items():
print(f'{k} is: {v}')
4. 单行 for 循环
您可以使用列表推导式来紧凑表示 for 循环。
- 例:
squares = [x**2 for x in range(10)]
print(squares)
5. 在列表推导式中添加 If 语句
您可以将if 语句与列表推导式组合在一起以过滤元素。
- 例:
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
6. 嵌套 For 循环
您还可以使用嵌套的 for 循环来迭代多维数据结构。
- 例:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for num in row:
print(num, end=' ')
print() # For newline after each row
- 此示例演示如何遍历具有嵌套 for 循环的 2D 列表(矩阵),并以矩阵格式打印每个数字。
输出:
1 2 3
4 5 6
7 8 9
7. 带有filter()的 For 循环
您可以将 filter() 函数与 for 循环一起使用,以仅处理满足特定条件的元素。
- 示例:
numbers = [1, 2, 3, 4, 5, 6]
for even in filter(lambda x: x % 2 == 0, numbers):
print(even)
输出:
2
4
6