Python语言核心22个必知语法细节

创作不易,如果本文对你有帮助,请动动你的手指点赞、转发、收藏吧!

对于刚入门学习Python还找不到方向的小伙伴可以试试我的这份学习方法和籽料,免费自取!!

1. 变量与数据类型

Python 是一种动态类型语言,这意味着你不需要声明变量的数据类型。你可以直接给变量赋值。

示例:

# 定义一个整型变量
age = 25
print("Age:", age)  # 输出 Age: 25

# 定义一个字符串变量
name = "Alice"
print("Name:", name)  # 输出 Name: Alice

# 定义一个浮点型变量
salary = 5000.50
print("Salary:", salary)  # 输出 Salary: 5000.5

解释:

  • age 是一个整型变量。

  • name 是一个字符串变量。

  • salary 是一个浮点型变量。

2. 字符串操作

字符串是 Python 中最常用的数据类型之一。你可以使用多种方法来操作字符串。

示例:

# 字符串拼接
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print("Full Name:", full_name)  # 输出 Full Name: John Doe

# 字符串重复
greeting = "Hello" * 3
print("Greeting:", greeting)  # 输出 Greeting: HelloHelloHello

# 字符串索引
word = "Python"
print("First letter:", word[0])  # 输出 First letter: P
print("Last letter:", word[-1])  # 输出 Last letter: n

# 字符串切片
print("Substring:", word[1:4])  # 输出 Substring: yth

解释:

  • + 操作符用于拼接字符串。

  • * 操作符用于重复字符串。

  • 索引和切片可以用来获取字符串中的特定字符或子字符串。

3. 列表 (List)

列表是一种常用的有序集合,可以包含不同类型的元素。

示例:

# 创建一个列表
fruits = ["apple", "banana", "cherry"]
print("Fruits:", fruits)  # 输出 Fruits: ['apple', 'banana', 'cherry']

# 访问列表元素
print("First fruit:", fruits[0])  # 输出 First fruit: apple
print("Last fruit:", fruits[-1])  # 输出 Last fruit: cherry

# 修改列表元素
fruits[1] = "orange"
print("Updated fruits:", fruits)  # 输出 Updated fruits: ['apple', 'orange', 'cherry']

# 添加元素
fruits.append("grape")
print("Appended fruits:", fruits)  # 输出 Appended fruits: ['apple', 'orange', 'cherry', 'grape']

# 删除元素
fruits.remove("cherry")
print("Removed fruits:", fruits)  # 输出 Removed fruits: ['apple', 'orange', 'grape']

解释:

  • 使用方括号 [] 来创建列表。

  • 使用索引来访问或修改列表中的元素。

  • append() 方法用于在列表末尾添加元素。

  • remove() 方法用于删除指定元素。

4. 元组 (Tuple)

元组与列表类似,但它是不可变的,一旦定义就不能修改。

示例:

# 创建一个元组
colors = ("red", "green", "blue")
print("Colors:", colors)  # 输出 Colors: ('red', 'green', 'blue')

# 访问元组元素
print("First color:", colors[0])  # 输出 First color: red

# 元组切片
print("Slice:", colors[1:])  # 输出 Slice: ('green', 'blue')

解释:

  • 使用圆括号 () 来创建元组。

  • 元组中的元素不能被修改。

  • 可以使用索引和切片来访问元组中的元素。

5. 字典 (Dictionary)

字典是一种键值对集合,常用于存储和检索数据。

示例:

# 创建一个字典
person = {"name": "Alice", "age": 25, "city": "New York"}
print("Person:", person)  # 输出 Person: {'name': 'Alice', 'age': 25, 'city': 'New York'}

# 访问字典元素
print("Name:", person["name"])  # 输出 Name: Alice

# 修改字典元素
person["age"] = 26
print("Updated person:", person)  # 输出 Updated person: {'name': 'Alice', 'age': 26, 'city': 'New York'}

# 添加新元素
person["job"] = "Engineer"
print("Added person:", person)  # 输出 Added person: {'name': 'Alice', 'age': 26, 'city': 'New York', 'job': 'Engineer'}

# 删除元素
del person["city"]
print("Deleted person:", person)  # 输出 Deleted person: {'name': 'Alice', 'age': 26, 'job': 'Engineer'}

解释:

  • 使用花括号 {} 来创建字典。

  • 使用键来访问或修改字典中的元素。

  • 可以使用 del 关键字来删除字典中的元素。

6. 控制结构 - if 语句

条件语句用于根据不同的条件执行不同的代码块。

示例:

# if 语句
age = 18
if age >= 18:
    print("You are an adult.")  # 输出 You are an adult.

# if-else 语句
if age < 18:
    print("You are a minor.")
else:
    print("You are an adult.")  # 输出 You are an adult.

# if-elif-else 语句
if age < 13:
    print("You are a child.")
elif age < 18:
    print("You are a teenager.")
else:
    print("You are an adult.")  # 输出 You are an adult.

解释:

  • if 语句用于检查条件是否为真。

  • if-else 语句用于在条件为真时执行一个代码块,在条件为假时执行另一个代码块。

  • if-elif-else 语句用于检查多个条件,并执行第一个为真的条件对应的代码块。

7. 控制结构 - for 循环

循环语句用于重复执行一段代码块。

示例:

# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
# 输出
# apple
# banana
# cherry

# 遍历字符串
word = "Python"
for char in word:
    print(char)
# 输出
# P
# y
# t
# h
# o
# n

# 使用 range() 函数
for i in range(5):
    print(i)
# 输出
# 0
# 1
# 2
# 3
# 4

解释:

  • for 循环可以遍历任何序列的项目,如列表或字符串。

  • range() 函数生成一系列数字,通常用于控制循环次数。

8. 控制结构 - while 循环

while 循环用于在条件为真时重复执行代码块。

示例:

# 基本 while 循环
count = 0
while count < 5:
    print(count)
    count += 1
# 输出
# 0
# 1
# 2
# 3
# 4

# 使用 break 和 continue
i = 0
while i < 10:
    if i == 5:
        break
    if i % 2 == 0:
        i += 1
        continue
    print(i)
    i += 1
# 输出
# 1
# 3
   

解释:

  • while 循环会在每次迭代前检查条件。

  • break 语句用于提前退出循环。

  • continue 语句用于跳过当前迭代并继续下一次迭代。

9. 函数

函数是一段可重用的代码块,可以接收参数并返回值。

示例:

# 定义一个函数
def greet(name):
    print(f"Hello, {name}!")

# 调用函数
greet("Alice")  # 输出 Hello, Alice!

# 返回值的函数
def add(a, b):
    return a + b

result = add(5, 3)
print("Result:", result)  # 输出 Result: 8

解释:

  • 使用 def 关键字定义函数。

  • 函数可以有参数。

  • 使用 return 语句返回值。

10. 参数传递方式

Python 中函数可以使用位置参数、关键字参数、默认参数等多种方式传递参数。

示例:

# 位置参数
def print_info(name, age):
    print(f"Name: {name}, Age: {age}")

print_info("Alice", 25)  # 输出 Name: Alice, Age: 25

# 关键字参数
print_info(age=25, name="Alice")  # 输出 Name: Alice, Age: 25

# 默认参数
def print_info(name, age=25):
    print(f"Name: {name}, Age: {age}")

print_info("Alice")  # 输出 Name: Alice, Age: 25

解释:

  • 位置参数按照参数顺序传递。

  • 关键字参数使用参数名称传递。

  • 默认参数可以在定义函数时指定默认值。

11. 变量作用域

变量的作用域决定了变量在程序中哪些地方可以被访问。

示例:

# 全局变量
x = 10

def test():
    global x
    x = 20
    print(x)  # 输出 20

test()
print(x)  # 输出 20

# 局部变量
def test():
    y = 5
    print(y)  # 输出 5

test()
# print(y)  # 报错,y 是局部变量

解释:

  • 全局变量在整个程序范围内都可以访问。

  • 局部变量只能在定义它的函数内部访问。

  • 使用 global 关键字可以在函数内部修改全局变量。

12. 异常处理

异常处理可以帮助程序更好地应对错误情况,避免程序崩溃。

示例:

# try-except 语句
try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print("Result:", result)
except ZeroDivisionError:
    print("Cannot divide by zero.")
except ValueError:
    print("Invalid input.")

# try-except-else 语句
try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Result:", result)

# try-except-finally 语句
try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero.")
finally:
    print("End of program.")

解释:

  • try 块用于尝试可能引发异常的代码。

  • except 块用于捕获并处理异常。

  • else 块在没有异常发生时执行。

  • finally 块无论是否有异常都会执行。

13. 类和对象

类是面向对象编程的基础,它定义了一组属性和方法。

示例:

# 定义一个简单的类
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"My name is {self.name} and I am {self.age} years old.")

# 创建一个对象
alice = Person("Alice", 25)
alice.introduce()  # 输出 My name is Alice and I am 25 years old.

# 创建另一个对象
bob = Person("Bob", 30)
bob.introduce()  # 输出 My name is Bob and I am 30 years old.

解释:

  • 使用 class 关键字定义类。

  • __init__ 方法是一个特殊的方法,用于初始化对象的属性。

  • 类中的方法可以通过对象调用。

14. 继承

继承允许一个类继承另一个类的属性和方法。

示例:

# 定义父类
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("An animal makes a sound.")

# 定义子类
class Dog(Animal):
    def speak(self):
        print("A dog says Woof!")

# 创建对象
animal = Animal("Generic Animal")
animal.speak()  # 输出 An animal makes a sound.

dog = Dog("Buddy")
dog.speak()  # 输出 A dog says Woof!

解释:

  • 子类 Dog 继承自父类 Animal

  • 子类可以覆盖父类的方法,实现多态性。

15. 多态

多态是指同一个方法在不同的对象上表现出不同的行为。

示例:

# 定义父类
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("An animal makes a sound.")

# 定义子类
class Dog(Animal):
    def speak(self):
        print("A dog says Woof!")

class Cat(Animal):
    def speak(self):
        print("A cat says Meow!")

# 创建对象
animals = [Dog("Buddy"), Cat("Whiskers")]

for animal in animals:
    animal.speak()
# 输出
# A dog says Woof!
# A cat says Meow!

解释:

  • 子类覆盖了父类的方法 speak

  • 在循环中,根据对象的实际类型调用相应的 speak 方法。

16. 类方法和静态方法

类方法和静态方法是类级别的方法,它们不依赖于具体的对象实例。

示例:

# 定义类方法
class MathUtils:
    @classmethod
    def add(cls, a, b):
        return a + b

# 使用类方法
result = MathUtils.add(5, 3)
print("Result:", result)  # 输出 Result: 8

# 定义静态方法
class MathUtils:
    @staticmethod
    def multiply(a, b):
        return a * b

# 使用静态方法
result = MathUtils.multiply(5, 3)
print("Result:", result)  # 输出 Result: 15

解释:

  • 类方法通过 @classmethod 装饰器定义,第一个参数通常是 cls,代表类本身。

  • 静态方法通过 @staticmethod 装饰器定义,不依赖于类或对象实例。

17. 内置函数

Python 提供了许多内置函数,用于处理各种常见的编程任务。

示例:

# len() 函数
fruits = ["apple", "banana", "cherry"]
print("Length:", len(fruits))  # 输出 Length: 3

# type() 函数
num = 5
print("Type:", type(num))  # 输出 Type: <class 'int'>

# sum() 函数
numbers = [1, 2, 3, 4, 5]
print("Sum:", sum(numbers))  # 输出 Sum: 15

# sorted() 函数
fruits = ["banana", "apple", "cherry"]
sorted_fruits = sorted(fruits)
print("Sorted:", sorted_fruits)  # 输出 Sorted: ['apple', 'banana', 'cherry']

解释:

  • len() 函数用于获取序列的长度。

  • type() 函数用于获取变量的数据类型。

  • sum() 函数用于计算数值列表的总和。

  • sorted() 函数用于对列表进行排序。

18. 生成器

生成器是一种特殊的迭代器,可以节省内存。

示例:

# 定义一个生成器函数
def fibonacci(n):
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a + b

# 使用生成器
for num in fibonacci(10):
    print(num)
# 输出
# 0
# 1
# 1
# 2
# 3
# 5
# 8

解释:

  • 使用 yield 关键字定义生成器函数。

  • 生成器函数每次调用时返回一个值,并保留状态。

19. Lambda 函数

Lambda 函数是一种简洁的匿名函数定义方式。

示例:

# 定义 lambda 函数
add = lambda x, y: x + y
print("Add:", add(5, 3))  # 输出 Add: 8

# 使用 lambda 函数
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", even_numbers)  # 输出 Even numbers: [2, 4]

解释:

  • lambda 关键字用于定义匿名函数。

  • Lambda 函数可以作为参数传递给其他函数,如 filter()

20. 列表推导式

列表推导式是一种简洁的创建列表的方式。

示例:

# 基本列表推导式
squares = [x ** 2 for x in range(5)]
print("Squares:", squares)  # 输出 Squares: [0, 1, 4, 9, 16]

# 带条件的列表推导式
even_squares = [x ** 2 for x in range(5) if x % 2 == 0]
print("Even squares:", even_squares)  # 输出 Even squares: [0, 4, 16]

解释:

  • 列表推导式使用 [expression for item in iterable] 的形式。

  • 可以在列表推导式中加入条件表达式。

21. 字典推导式

字典推导式是一种简洁的创建字典的方式。

示例:

# 基本字典推导式
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
age_dict = {name: age for name, age in zip(names, ages)}
print("Age dict:", age_dict)  # 输出 Age dict: {'Alice': 25, 'Bob': 30, 'Charlie': 35}

# 带条件的字典推导式
even_age_dict = {name: age for name, age in zip(names, ages) if age % 2 == 0}
print("Even age dict:", even_age_dict)  # 输出 Even age dict: {'Alice': 25, 'Charlie': 35}

解释:

  • 字典推导式使用 {key_expression: value_expression for item in iterable} 的形式。

  • 可以在字典推导式中加入条件表达式。

22. 装饰器

装饰器是一种函数,可以修改其他函数的行为。

示例:

# 定义一个装饰器
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()
# 输出
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.

解释:

  • 装饰器是一个接受函数作为参数的函数。

  • 使用 @decorator 语法将装饰器应用到函数上。

实战案例:学生信息管理系统

假设我们需要开发一个简单的学生信息管理系统,系统需要能够添加学生信息、查询学生信息、删除学生信息等功能。

需求分析:1. 添加学生信息(姓名、年龄、班级)。2. 查询学生信息。3. 删除学生信息。

代码实现:

# 定义学生类
class Student:
    def __init__(self, name, age, class_name):
        self.name = name
        self.age = age
        self.class_name = class_name

    def display(self):
        print(f"Name: {self.name}, Age: {self.age}, Class: {self.class_name}")

# 学生信息管理类
class StudentManager:
    def __init__(self):
        self.students = []

    def add_student(self, name, age, class_name):
        student = Student(name, age, class_name)
        self.students.append(student)
        print(f"Student {name} added successfully.")

    def find_student(self, name):
        for student in self.students:
            if student.name == name:
                student.display()
                return
        print(f"Student {name} not found.")

    def delete_student(self, name):
        for student in self.students:
            if student.name == name:
                self.students.remove(student)
                print(f"Student {name} deleted successfully.")
                return
        print(f"Student {name} not found.")

# 主函数
def main():
    manager = StudentManager()

    while True:
        print("\nStudent Management System")
        print("1. Add Student")
        print("2. Find Student")
        print("3. Delete Student")
        print("4. Exit")

        choice = input("Enter your choice: ")

        if choice == "1":
            name = input("Enter student name: ")
            age = int(input("Enter student age: "))
            class_name = input("Enter student class: ")
            manager.add_student(name, age, class_name)
        elif choice == "2":
            name = input("Enter student name to find: ")
            manager.find_student(name)
        elif choice == "3":
            name = input("Enter student name to delete: ")
            manager.delete_student(name)
        elif choice == "4":
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()

解释:

  • 定义了一个 Student 类,包含学生的姓名、年龄和班级信息。

  • 定义了一个 StudentManager 类,用于管理学生信息。

  • StudentManager 类提供了添加学生、查找学生和删除学生的方法。

  • 主函数提供了一个简单的用户界面,让用户选择操作。

好了,今天的分享就到这里了,我们下期见。

文末福利

最后,我精心筹备了一份全面的Python学习大礼包,完全免费分享给每一位渴望成长、希望突破自我现状却略感迷茫的朋友。无论您是编程新手还是希望深化技能的开发者,都欢迎加入我们的学习之旅,共同交流进步!

学习大礼包包含内容:

Python全领域学习路线图:一目了然,指引您从基础到进阶,再到专业领域的每一步学习路径,明确各方向的核心知识点。

超百节Python精品视频课程:涵盖Python编程的必备基础知识、高效爬虫技术、以及深入的数据分析技能,让您技能全面升级。

实战案例集锦:精选超过100个实战项目案例,从理论到实践,让您在解决实际问题的过程中,深化理解,提升编程能力。

华为独家Python漫画教程:创新学习方式,以轻松幽默的漫画形式,让您随时随地,利用碎片时间也能高效学习Python。

互联网企业Python面试真题集:精选历年知名互联网企业面试真题,助您提前备战,面试准备更充分,职场晋升更顺利。

 

猜你喜欢

转载自blog.csdn.net/m0_62283350/article/details/142959286