掌握 Python 的七種常用數據類型
在Python編程的世界里,數據類型是構建程序大廈的基石。掌握Python的常用數據類型,能幫助你更高效地處理數據和編寫代碼。今天,我們就來詳細探討Python中的7種常用數據類型:整數(Integer)、浮點數(Float)、字符串(String)、布爾值(Boolean)、列表(List)、元組(Tuple)和字典(Dictionary)。
1. 整數(Integer)
整數是最基本的數據類型之一,用于表示沒有小數部分的數字。在Python中,整數的范圍非常大,幾乎可以處理任何大小的整數。
代碼示例:
# 定義一個整數
a = 10
b = -5
# 輸出整數
print(a) # 輸出: 10
print(b) # 輸出: -5
# 整數運算
sum = a + b
print(sum) # 輸出: 5
2. 浮點數(Float)
浮點數用于表示有小數部分的數字。在Python中,浮點數通常以科學計數法或十進制表示。
代碼示例:
# 定義一個浮點數
pi = 3.14
gravity = 9.81
# 輸出浮點數
print(pi) # 輸出: 3.14
print(gravity) # 輸出: 9.81
# 浮點數運算
area = pi * (5 ** 2) # 計算半徑為5的圓的面積
print(area) # 輸出: 78.5
3. 字符串(String)
字符串是由一系列字符組成的序列,用于表示文本數據。在Python中,字符串用單引號(')、雙引號(")或三引號('''或""")括起來。
代碼示例:
# 定義一個字符串
greeting = "Hello, World!"
quote = 'To be or not to be, that is the question.'
multiline = """This is a multi-line
string."""
# 輸出字符串
print(greeting) # 輸出: Hello, World!
print(quote) # 輸出: To be or not to be, that is the question.
print(multiline) # 輸出:
# This is a multi-line
# string.
# 字符串操作
length = len(greeting)
print(length) # 輸出: 13
upper_greeting = greeting.upper()
print(upper_greeting) # 輸出: HELLO, WORLD!
4. 布爾值(Boolean)
布爾值是一種特殊的數據類型,只有兩個值:True和False。布爾值常用于條件判斷和邏輯運算。
代碼示例:
# 定義布爾值
is_raining = True
is_sunny = False
# 輸出布爾值
print(is_raining) # 輸出: True
print(is_sunny) # 輸出: False
# 布爾運算
and_result = is_raining and is_sunny
or_result = is_raining or is_sunny
print(and_result) # 輸出: False
print(or_result) # 輸出: True
5. 列表(List)
列表是Python中的一種可變序列類型,可以包含多個項目,這些項目可以是不同類型的數據。列表用方括號[]表示。
代碼示例:
# 定義一個列表
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, 'two', 3.0, True]
# 輸出列表
print(fruits) # 輸出: ['apple', 'banana', 'cherry']
print(numbers) # 輸出: [1, 2, 3, 4, 5]
print(mixed_list) # 輸出: [1, 'two', 3.0, True]
# 列表操作
fruits.append('date')
print(fruits) # 輸出: ['apple', 'banana', 'cherry', 'date']
length = len(numbers)
print(length) # 輸出: 5
6. 元組(Tuple)
元組與列表類似,也是序列類型,但元組是不可變的,即一旦創建,就不能修改其內容。元組用圓括號()表示。
代碼示例:
# 定義一個元組
coordinates = (10, 20)
colors = ('red', 'green', 'blue')
# 輸出元組
print(coordinates) # 輸出: (10, 20)
print(colors) # 輸出: ('red', 'green', 'blue')
# 元組是不可變的
# coordinates[0] = 15 # 這行代碼會引發錯誤
7. 字典(Dictionary)
字典是Python中的另一種可變類型,用于存儲鍵值對。字典用花括號{}表示,每個鍵值對之間用冒號:分隔,不同鍵值對之間用逗號,分隔。
代碼示例:
# 定義一個字典
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
# 輸出字典
print(person) # 輸出: {'name': 'Alice', 'age': 30, 'city': 'New York'}
# 訪問字典中的值
name = person['name']
print(name) # 輸出: Alice
# 修改字典中的值
person['age'] = 31
print(person) # 輸出: {'name': 'Alice', 'age': 31, 'city': 'New York'}
# 添加新的鍵值對
person['job'] = 'Engineer'
print(person) # 輸出: {'name': 'Alice', 'age': 31, 'city': 'New York', 'job': 'Engineer'}
實戰案例:學生信息管理系統
現在,我們利用上述數據類型來構建一個簡單的學生信息管理系統。這個系統將能夠存儲學生的姓名、年齡和成績,并允許我們查詢和更新學生的信息。
代碼示例:
# 定義一個字典來存儲學生信息
students = {
'Alice': {'age': 20, 'grades': [85, 90, 88]},
'Bob': {'age': 22, 'grades': [78, 82, 85]},
'Charlie': {'age': 21, 'grades': [92, 95, 90]}
}
# 查詢學生信息
def query_student(student_name):
if student_name in students:
student_info = students[student_name]
print(f"Name: {student_name}")
print(f"Age: {student_info['age']}")
print(f"Grades: {student_info['grades']}")
average_grade = sum(student_info['grades']) / len(student_info['grades'])
print(f"Average Grade: {average_grade:.2f}")
else:
print(f"Student {student_name} not found.")
# 更新學生成績
def update_grade(student_name, subject_index, new_grade):
if student_name in students:
if 0 <= subject_index < len(students[student_name]['grades']):
students[student_name]['grades'][subject_index] = new_grade
print(f"Updated grade for {student_name} in subject {subject_index} to {new_grade}.")
else:
print(f"Invalid subject index for {student_name}.")
else:
print(f"Student {student_name} not found.")
# 示例操作
query_student('Alice')
update_grade('Bob', 1, 88)
query_student('Bob')
輸出示例:
Name: Alice
Age: 20
Grades: [85, 90, 88]
Average Grade: 87.67
Updated grade for Bob in subject 1 to 88.
Name: Bob
Age: 22
Grades: [78, 88, 85]
Average Grade: 83.67
在這個實戰案例中,我們使用了字典來存儲學生信息,其中每個學生的信息又是一個字典,包含了年齡和成績列表。通過定義query_student和update_grade函數,我們能夠方便地查詢和更新學生的信息。
總結
本篇文章詳細介紹了Python中的7種常用數據類型:整數、浮點數、字符串、布爾值、列表、元組和字典。每種數據類型都通過代碼示例進行了詳細闡述,并提供了相應的輸出結果和代碼注釋,幫助讀者理解其工作原理和功能。最后,通過構建一個學生信息管理系統的實戰案例,展示了這些數據類型在實際編程中的應用。希望讀者能夠通過本文的學習,掌握Python的基本數據類型,并在實際編程中靈活運用。