一、變量與數據類型
Python語言中,變量的命名需遵循一定的規則,如只能由數字、字母、下劃線組成,且不能以數字開頭。Python支持多種數據類型,包括整型、浮點型、布爾型、字符串、列表、元組、字典等。
# 變量命名規則示例
score_1 = 90
Score1 = 85
Score1_ = 92
# 數據類型示例
a = 10 # 整型
b = 2.5 # 浮點型
c = False # 布爾型
d = 'Hello World' # 字符串
e = [1, 2, 3] # 列表
f = (1, 2, 3) # 元組
g = {'name': 'Alice', 'age': 20} # 字典
二、條件與循環
Python語言中,條件和循環語句是非常常用的語句。條件語句用於根據條件判斷是否執行某個語句塊,循環語句則重複執行某個語句塊。
# 條件語句示例
age = 18
if age >= 18:
print('成年人')
else:
print('未成年人')
# 循環語句示例
for i in range(1, 6):
print(i)
while True:
print('循環中')
break # 跳出循環
三、函數與模塊
函數和模塊是Python語言中的兩個核心概念。函數用於封裝代碼,可以提高代碼的復用性和可讀性;模塊則是包含Python代碼的文件,可以被其他程序引用。
# 函數示例
def add(a, b):
return a + b
result = add(3, 5)
print(result)
# 模塊示例
# 模塊文件mymodule.py內容
def say_hello(name):
print('Hello, ' + name)
# 程序文件中引用模塊
import mymodule
mymodule.say_hello('Alice')
四、字符串操作
字符串操作在Python中非常常用,包括字符串連接、字符串格式化、字符串查找等。
# 字符串連接示例
str1 = 'Hello'
str2 = 'World'
result = str1 + ' ' + str2
print(result)
# 字符串格式化示例
name = 'Alice'
age = 20
result = 'My name is %s, age is %d' % (name, age)
print(result)
# 字符串查找示例
str1 = 'Hello World'
if 'World' in str1:
print('找到了!')
五、文件操作
Python提供了豐富的文件操作函數,包括文件創建、文件打開、文件讀寫、文件刪除等。
# 文件寫操作示例
f = open('test.txt', 'w')
f.write('Hello World')
f.close()
# 文件讀操作示例
f = open('test.txt', 'r')
content = f.read()
print(content)
f.close()
# 文件刪除示例
import os
os.remove('test.txt')
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/201180.html
微信掃一掃
支付寶掃一掃