30天學會Python編程:2. Python基礎語法結構
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
|
student_name | ||
MAX_COUNT | ||
ClassName | ||
module_name.py |
name
≠ Name
1var
?class = 5
?str = "hello"
?函數原型:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
參數說明:
objects:要輸出的對象,多個用逗號分隔
sep:分隔符,默認空格
end:結束字符,默認換行
file:輸出目標,默認標準輸出
flush:是否立即刷新緩沖區
實用示例:
# 格式化輸出
name = "Alice"
age = 25
print(f"{name} is {age} years old") # f-string (Python 3.6+)
# 多參數輸出
print("Value:", 10, "Type:", type(10), sep="|", end="!\n")
# 輸出:Value:|10|Type:|<class 'int'>!
函數原型:
input(prompt='') -> str
使用示例:
name = input("請輸入你的名字:")
print(f"你好,{name}!")
# 類型轉換
age = int(input("請輸入年齡:"))
注意事項:
Python 3.10共有35個關鍵字:
import keyword
print(keyword.kwlist)
表2 主要關鍵字分類
# 條件判斷示例
if age >= 18:
print("成年人")
elif age >= 12:
print("青少年")
else:
print("兒童")
# 循環控制示例
for i inrange(5):
if i == 3:
continue
print(i)
# 用戶登錄系統
MAX_ATTEMPTS = 3
correct_password = "python123"
attempts = 0
while attempts < MAX_ATTEMPTS:
password = input("請輸入密碼:")
if password == correct_password:
print("登錄成功!")
break
else:
attempts += 1
print(f"密碼錯誤,還剩{MAX_ATTEMPTS - attempts}次機會")
else:
print("賬戶已鎖定,請聯系管理員")
def celsius_to_fahrenheit(celsius):
"""攝氏溫度轉華氏溫度
Args:
celsius (float): 攝氏溫度值
Returns:
float: 華氏溫度值
"""
return celsius * 9/5 + 32
# 用戶交互
try:
temp_c = float(input("請輸入攝氏溫度:"))
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}℃ = {temp_f:.1f}℉") # 保留1位小數
except ValueError:
print("請輸入有效的數字!")
縮進錯誤:
def func():
print("縮進錯誤") # IndentationError
語法缺失:
if True # 缺少冒號
print("Hello")
命名沖突:
import = 10 # 使用關鍵字作為變量名
print()
輸出中間值python -i script.py
)
核心要點:
實踐建議:
進階方向:
常見陷阱:
閱讀原文:原文鏈接