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