20個 Python 入門基礎語法要點
天,我們將聚焦于Python的20個基礎語法要點,讓你的編程之旅更加順暢。
第一部分:環(huán)境搭建與基本概念
1. Hello, World!
你的第一行代碼:這是編程旅程的傳統(tǒng)起點。
print("Hello, World!")
這行代碼告訴Python顯示文本,print是關鍵函數(shù),用于輸出信息。
2. 變量與賦值
存儲信息的盒子:
message = "學習Python很有趣"
print(message)
變量就像容器,用來保存數(shù)據(jù),這里message保存了字符串。
3. 數(shù)據(jù)類型
數(shù)字游戲:
number = 42
float_number = 3.14
print(number, float_number)
Python有多種數(shù)據(jù)類型,如整型(int)和浮點型(float)。
4. 字符串操作
拼接與切片:
greeting = "你好"
name = "世界"
print(greeting + ", " + name + "!")
# 切片
slice_example = "Python"[0:5]
print(slice_example)
字符串可以用加號合并,方括號用于切片。
5. 條件判斷
做決定:
age = 18
if age >= 18:
print("成年了")
else:
print("未成年")
根據(jù)條件執(zhí)行不同的代碼塊。
6. 循環(huán)
重復的藝術:
for i in range(5):
print(i)
range()生成數(shù)字序列,for循環(huán)遍歷這些數(shù)字。
7. 列表(Lists)
有序集合:
my_list = [1, 2, 3, 4, 5]
print(my_list[1]) # 訪問元素
列表是可變的,可以包含不同類型的元素。
8. 列表推導式
優(yōu)雅的創(chuàng)建列表:
squares = [i**2 for i in range(1, 6)]
print(squares)
一行代碼生成平方數(shù)列表,高效且易讀。
第二部分:進階基礎
9. 字典(Dictionaries)
鍵值對的世界:
person = {"name": "小明", "age": 24}
print(person["name"])
字典用花括號表示,鍵與值之間用冒號分隔。
10. 元組(Tuples)
不可變序列:
coordinates = (3, 4)
print(coordinates[0])
元組一旦創(chuàng)建就無法修改,常用于表示不可變的數(shù)據(jù)集合。
11. 函數(shù)(Function)
封裝與重用:
def greet(name):
return f"你好,{name}!"
print(greet("世界"))
定義函數(shù)以執(zhí)行特定任務,提升代碼組織性。
12. 模塊(Module)
代碼的分裝:
import math
print(math.sqrt(16))
模塊是預寫好的代碼集合,通過import引入使用其功能。
13. 異常處理
錯誤管理:
try:
num = int(input("請輸入一個數(shù)字: "))
print(10 / num)
except ZeroDivisionError:
print("不能除以零!")
try-except結構幫助你優(yōu)雅地處理程序中的錯誤。
14. 導入特定功能
精準引入:
from math import sqrt
print(sqrt(25))
僅導入模塊中的特定函數(shù),減少命名空間污染。
15. 列表解包
從列表到變量:
a, b = [1, 2]
print(a, b)
將列表的元素分配給多個變量。
16. 列表的高級操作
**map()與filter()**:
numbers = [1, 2, 3, 4]
# 使用map()
squared = list(map(lambda x: x**2, numbers))
print(squared)
# 使用filter()
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
這兩個函數(shù)分別用于轉換和篩選列表元素。
第三部分:高級概念與實踐
17. 類與對象(Object-Oriented Programming, OOP)
面向對象編程的基石:
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def display(self):
print(f"學生: {self.name}, 成績: {self.grade}")
student1 = Student("小紅", 95)
student1.display()
類定義了對象的結構和行為,__init__是構造函數(shù),用于初始化對象。
18. 繼承(Inheritance)
擴展類的功能:
class HonorStudent(Student):
def __init__(self, name, grade, scholarship):
super().__init__(name, grade)
self.scholarship = scholarship
def display(self):
super().display()
print(f"獎學金: {self.scholarship}")
honor_student = HonorStudent("小藍", 99, True)
honor_student.display()
HonorStudent繼承自Student,super()用于調用父類的方法。
19. 迭代器與生成器(Iterators & Generators)
高效處理大量數(shù)據(jù):
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for number in count_up_to(5):
print(number)
生成器通過yield關鍵字實現(xiàn),按需產生值,內存友好。
20. 裝飾器(Decorators)
函數(shù)的增強劑:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
裝飾器允許不修改原函數(shù)的情況下增加新功能,用@符號應用。