【Python知识点复习】

一、Python数据类型

Python中有多种数据类型,每种数据类型都有其特定的用途和行为。以下是一些主要的数据类型:

  1. 整数(int):表示整数,例如 10-3
  2. 浮点数(float):表示小数,例如 3.14-2.718
  3. 字符串(str):表示文本,例如 "Hello, World!""Python编程"
  4. 布尔值(bool):表示真或假,只有两个值 TrueFalse
  5. 列表(list):有序的元素集合,可以包含不同类型的元素,例如 [1, 2, 3]["apple", "banana", "cherry"]
  6. 元组(tuple):与列表类似,但一旦创建便不可修改,例如 (1, 2, 3)("apple", "banana", "cherry")
  7. 字典(dict):键值对的无序集合,例如 {"name": "Alice", "age": 25}
  8. 集合(set):无序且不重复的元素集合,例如 {1, 2, 3}{"apple", "banana", "cherry"}
  9. NoneType:表示空值或缺失值,例如 None
下面是一个示例代码,用type()函数来查看并输出一些变量的数据类型,以及预输出结果:

 # 数字类型
a = 10
print(type(a))  # 预输出: <class 'int'>

b = 3.14
print(type(b))  # 预输出: <class 'float'>

c = 1 + 2j
print(type(c))  # 预输出: <class 'complex'>

# 字符串类型
d = "hello"
print(type(d))  # 预输出: <class 'str'>

# 布尔类型
e = True
print(type(e))  # 预输出: <class 'bool'>

# 列表类型
f = [1, 2, 3]
print(type(f))  # 预输出: <class 'list'>

# 元组类型
g = (1, 2, 3)
print(type(g))  # 预输出: <class 'tuple'>

# 字典类型
h 
### Python 函数期末考试复习要点 #### 定义与调用 函数定义使用 `def` 关键字,后面跟上函数名和参数列表。函数体由冒号引导并缩进表示[^1]。 ```python def greet(name): print(f'Hello, {name}') greet('Alice') ``` #### 参数传递 Python 支持多种类型的参数传递方式,包括位置参数、关键字参数以及默认值参数。 ```python def connect(db='test', user='root'): print(f'Database: {db}, User: {user}') connect(user='admin') # 使用关键字参数指定特定参数的值 ``` #### 返回值 通过 `return` 语句返回计算结果给调用者;如果没有显式的 `return` 或仅写 `return` 则相当于返回 `None`。 ```python def add(a, b): return a + b result = add(3, 5) print(result) # 输出8 ``` #### 变量作用域 局部变量只在其所属代码块内有效(如循环体内),而全局变量在整个模块范围内都可访问。可以利用 `global` 和 `nonlocal` 声明来改变这一行为。 ```python x = 'outside' def func(): global x x = 'inside' func() print(x) # 输出 "inside" ``` #### Lambda 表达式 匿名函数允许快速创建简单的单行函数对象,通常用于临时性的操作处理场景中。 ```python double = lambda n : n * 2 print(double(7)) ``` #### 高阶函数 高阶函数是指接受其他函数作为输入或将函数作为输出的一部分的功能强大的工具之一。常见的内置高阶函数有 `map()`、`filter()` 等。 ```python numbers = [1, 2, 3] squared_numbers = list(map(lambda x: x ** 2, numbers)) even_numbers = list(filter(lambda x: x % 2 == 0, squared_numbers)) print(squared_numbers) # [1, 4, 9] print(even_numbers) # [4] ``` #### 装饰器 装饰器本质上是一个接收另一个函数作为参数并将某些功能附加到该目标上的特殊形式闭包。这有助于实现诸如日志记录等功能增强而不修改原始逻辑结构。 ```python from functools import wraps def log_decorator(func): @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) print(f'{func.__name__} called with arguments {args} and returned {result}.') return result return wrapper @log_decorator def multiply(x, y): return x * y multiply(6, 7) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值