一、數據類型
Python是一種解釋型、動態的、面向對象的高級編程語言。在Python中,變數的數據類型不需要聲明。Python支持多種數據類型。常見的包括:
- 整型:int
- 浮點型:float
- 布爾型:bool
- 字元串:str
- 列表:list
- 元組:tuple
- 集合:set
- 字典:dict
# 數據類型舉例
a = 10 # 整型
b = 3.14 # 浮點型
c = True # 布爾型
d = "hello" # 字元串
e = [1, 2, 3] # 列表
f = (4, 5, 6) # 元組
g = {7, 8, 9} # 集合
h = {"name": "Tom", "age": 18} # 字典
二、控制流語句
控制流語句是編程中常用的語法結構,常用的有:
- if-elif-else語句:根據條件執行不同的代碼塊
- for循環語句:循環執行一段代碼,可對列表、元組、集合、字典等進行遍歷
- while循環語句:當條件滿足時,循環執行一段代碼
- break和continue語句:break結束循環,continue跳過本次循環
# 控制流語句舉例
a = 10
if a > 5:
print("a大於5")
elif a == 5:
print("a等於5")
else:
print("a小於5")
b = ["apple", "banana", "pear"]
for fruit in b:
print(fruit)
c = 0
while c < 5:
print(c)
c += 1
d = ["red", "yellow", "green"]
for color in d:
if color == "yellow":
continue
print(color)
if color == "green":
break
三、函數
函數是一段可重用的代碼塊,可接收參數和返回值。Python提供了豐富的內置函數,也可以自定義函數。函數的定義格式為:
def function_name(parameter1, parameter2):
# 函數體
return value
其中,def表示定義函數,function_name為函數名,parameter為參數列表,return為返回值。
# 函數舉例
def add(x, y):
return x + y
z = add(3, 5)
print(z)
四、文件操作
Python的文件操作主要有打開、讀取、寫入和關閉。文件打開的模式包括只讀(’r’)、只寫(’w’)、追加(’a’)和讀寫(’r+’)等。
# 文件操作舉例
# 打開文件
f = open("test.txt", "w")
# 寫入文件
f.write("hello world!")
# 關閉文件
f.close()
# 打開文件
f = open("test.txt", "r")
# 讀取文件
content = f.read()
print(content)
# 關閉文件
f.close()
五、模塊和包
Python的模塊和包是代碼組織和管理的方便工具。模塊是一個包含代碼的文件,而包是多個模塊的集合。Python提供了訪問模塊和包中代碼的方法。
# 模塊和包舉例
# 導入模塊
import math
print(math.pi)
# 導入包中模塊
import os.path
print(os.path.abspath("test.txt"))
原創文章,作者:MKGQE,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/370258.html