Python 数据类型:数字、字符串与容器
<p>数据是程序的核心。Python 提供了丰富且易用的内置数据类型,本文带你系统掌握最常用的几类。</p><h2>一、数字类型</h2>
<p>Python 支持三种基本数字类型:</p>
<pre># 整数 (int)
age = 25
count = -100
# 浮点数 (float)
price = 19.99
pi = 3.14159</pre>
<p><strong>常用数字运算:</strong></p>
<pre>a, b = 17, 5
print(a + b) # 加法: 22
print(a - b) # 减法: 12
print(a * b) # 乘法: 85
print(a / b) # 除法: 3.4</pre>
<h2>二、字符串 (str)</h2>
<p>字符串是 Python 中最常用的数据类型之一。</p>
<pre># 创建字符串
s1 = 'Hello'
s2 = "World"
# f-string (推荐)
version = 3.12
info = f"当前 Python 版本是 {version}"</pre>
<h2>三、列表 (list)</h2>
<p>列表是 Python 最常用的容器类型,有序且可变。</p>
<pre>fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.sort()</pre>
<h2>四、元组 (tuple)</h2>
<p>元组与列表类似,但<strong>不可变</strong>。</p>
<pre>point = (3, 4)
x, y = point# 元组解包</pre>
<h2>五、字典 (dict)</h2>
<p>字典是键值对集合,查找极快。</p>
<pre>person = {"name": "Alice", "age": 30}
print(person.get("salary", "Unknown"))</pre>
<h2>六、集合 (set)</h2>
<p>集合是无序、不重复的元素集。</p>
<pre>a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)# 并集
print(a & b)# 交集</pre>
<h2>七、总结</h2>
<p>掌握这些数据类型,你就拥有了处理各种数据的基础能力!</p><br><br>
来源:https://www.cnblogs.com/cartech/p/19752081
頁:
[1]