2024-05-15 · 阅读约 8 分钟 · 阅读

1. python介绍

高级编程语言(解释型)

  • C/C++语言、Java等都是编译型语言
  • 解释型语言没有编译器,一条一条地解释,动态语言,边解释边分配内存
  • Python使用缩进控制域
  • Python的所有数据类型都是”对象“

简介、易读、更接近自然语言

Python的数据类型

  • 不同于C语言,Python不需要显式声明数据类型
  • Python的’‘(单引号)和”“(双引号)一般认为没有区别
  • Python的强制类型转换格式为: int() float() str()

  • Python的类采用的思想是鸭子类型,即“如果看起来像鸭子,叫起来像鸭子,那么它就是鸭子”

2. 控制结构

条件语句

  • if、else、elif
  • # 示例代码
    x = 10
    if x > 5:
        print("x 大于 5")
    elif x == 5:
        print("x 等于 5")
    else:
        print("x 小于 5")
    
    

循环语句

  1. for
  • for循环用于遍历序列(如列表、元组、字符串等)
  • # 示例代码1
    fruits = ["apple", "banana", "cherry"]
    for fruit in fruits:
        print(fruit)
    
    # 示例代码1
    for num in range(3):
    	print(num) 
    # 0
    # 1
    # 2
    
  1. while
  • while循环在条件为真时反复执行代码块。
  • # 示例代码
    count = 0
    while count < 5:
        print(count)
        count += 1
    
    

控制流

  1. break
  • break语句用于提前退出循环。
  • # 示例代码
    for i in range(10):
        if i == 5:
            break
        print(i)
    
    # 1
    # 2
    # 3
    # 4
    
  1. continue
  • continue语句用于跳过当前迭代并继续下一次迭代。
  • # 示例代码
    for i in range(10):
        if i % 2 == 0:
            continue
        print(i)
    # 1
    # 3
    # 5
    # 7
    # 9
    
  1. pass
  • pass语句用于占位,表示什么都不做。
  • # 示例代码
    for i in range(10):
        pass
    

类似于C语言中的空语句

if (condition)
    ;

3. 函数

  • 函数是组织代码的重要方式,它们可以让代码更加模块化和易于维护。函数可以执行特定的任务并返回结果。

定义函数

  • 在Python中,可以使用def关键字来定义函数。函数名后跟一对圆括号和一个冒号,函数体缩进。
  • # 示例代码
    # 无返回值 相当于C语言void函数
    def greet(name):
        print(f"Hello, {name}!") # print("Hello, {}!".format(name))
    
    # 调用函数
    greet("Alice")
    
    

返回值

  • 函数可以使用return语句返回一个值。
  • # 示例代码
    def add(a, b):
        return a + b
    
    # 调用函数并存储返回值
    result = add(3, 5)
    print(result)  # 输出 8
    
    

默认参数值

  • 可以为函数参数指定默认值,如果调用函数时未提供该参数,则使用默认值。
  • # 示例代码
    def greet(name="Guest"):
        print(f"Hello, {name}!")
    
    # 调用函数
    greet()          # 输出 Hello, Guest!
    greet("Alice")   # 输出 Hello, Alice!
    
    

可变参数

  • 可以使用*args**kwargs来定义可变参数的函数,*args用于接收任意数量的位置参数,**kwargs用于接收任意数量的关键字参数。
  • # 示例代码
    def print_args(*args):
        for arg in args:
            print(arg)
    
    print_args(1, 2, 3)
    
    def print_kwargs(**kwargs):
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    
    print_kwargs(name="Alice", age=30)
    
    

嵌套函数和闭包

  • 可以在函数内部定义函数,这种函数称为嵌套函数。闭包是指内部函数引用了外部函数的变量,并且外部函数已经返回。

  • # 示例代码
    def outer_function(msg):
        def inner_function():
            print(msg)
        return inner_function
    
    closure = outer_function("Hello")
    closure()  # 输出 Hello
    
    
  • 闭包是一个非常有用的编程概念,它可以在许多情况下提升代码的可读性、可维护性和灵活性。以下是闭包的几个主要用途:

1. 数据封装

闭包可以用来封装数据,提供一种实现数据隐藏和保护的方式。这类似于面向对象编程中的私有属性。

def make_counter():
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter

# 创建一个计数器实例
my_counter = make_counter()
print(my_counter())  # 输出 1
print(my_counter())  # 输出 2

在这个示例中,count变量被封装在make_counter函数中,只有内部的counter函数可以访问和修改它。

2. 回调函数

闭包常用于回调函数中,尤其是在异步编程和事件驱动编程中。

def create_callback(message):
    def callback():
        print(message)
    return callback

callback_hello = create_callback("Hello, World!")
callback_hello()  # 输出 Hello, World!

在这个示例中,callback函数作为一个回调函数,能够记住并使用create_callback函数的参数message

3. 高阶函数

闭包可以用于创建高阶函数,即返回另一个函数的函数。这在函数式编程中非常常见。

def multiplier(factor):
    def multiply(number):
        return number * factor
    return multiply

times_two = multiplier(2)
times_three = multiplier(3)

print(times_two(5))  # 输出 10
print(times_three(5))  # 输出 15

在这个示例中,multiplier函数返回一个新的函数multiply,该函数将输入的数字乘以一个特定的因子。

4. 延迟求值

闭包可以用于延迟求值,即在需要时才计算结果,而不是在定义时就计算。这在某些性能优化中非常有用。

def make_lazy_add(a, b):
    def lazy_add():
        return a + b
    return lazy_add

lazy_add_function = make_lazy_add(2, 3)
print(lazy_add_function())  # 输出 5

在这个示例中,lazy_add函数只有在被调用时才计算a + b的值。

5. 状态持久化

闭包可以用来持久化某些状态,而不需要使用全局变量。这对于构建状态机或管理复杂的状态非常有用。

def create_accumulator():
    total = 0

    def add(value):
        nonlocal total
        total += value
        return total

    return add

accumulator = create_accumulator()
print(accumulator(10))  # 输出 10
print(accumulator(5))   # 输出 15

在这个示例中,total变量的状态在多次调用add函数之间得以持久化。

匿名函数

  • 匿名函数是一种没有名字的函数,通常用于简单的操作。
  • # 示例代码
    add = lambda a, b: a + b
    print(add(3, 5))  # 输出 8
    

匿名函数在c语言中不存在,是python的特色。原因是python的函数是对象,可以赋值给变量,而匿名函数就是没有名字的函数对象。而c语言的函数是语句,不能赋值给变量。

4. 数据结构

  • Python 提供了多种内置的数据结构,用于存储和组织数据。我们将详细介绍以下几种常见的数据结构:列表、元组、字典和集合。

列表

  • 列表是一种有序的可变序列,可以存储任意类型的元素。
# 创建列表
fruits = ["apple", "banana", "cherry"]

# 访问元素
print(fruits[0])  # 输出 "apple"

# 修改元素
fruits[1] = "blueberry"

# 添加元素
fruits.append("date")

# 删除元素
fruits.remove("apple")

# 遍历列表
for fruit in fruits:
    print(fruit)

元组

  • 元组是一种有序的不可变序列,一旦创建就不能修改。
  • # 创建元组
    coordinates = (10.0, 20.0)
    
    # 访问元素
    print(coordinates[0])  # 输出 10.0
    
    # 遍历元组
    for coordinate in coordinates:
        print(coordinate)
    
    
  • 元组通常用于存储不需要修改的数据,例如地理坐标或数据库记录。

字典

  • 字典是一种无序的可变映射,使用键-值对来存储数据。
  • # 创建字典
    student = {"name": "Alice", "age": 25, "major": "Computer Science"}
    
    # 访问值
    print(student["name"])  # 输出 "Alice"
    
    # 修改值
    student["age"] = 26
    
    # 添加键-值对
    student["grade"] = "A"
    
    # 删除键-值对
    del student["major"]
    
    # 遍历字典
    for key, value in student.items():
        print(f"{key}: {value}")
    
    

集合

  • 集合是一种无序的可变集合,不允许重复元素。
  • # 创建集合
    numbers = {1, 2, 3, 4}
    
    # 添加元素
    numbers.add(5)
    
    # 删除元素
    numbers.remove(3)
    
    # 集合运算
    odds = {1, 3, 5, 7}
    evens = {2, 4, 6, 8}
    union = odds | evens      # 并集
    intersection = odds & evens  # 交集
    
    # 遍历集合
    for number in numbers:
        print(number)
    
    
  • 集合的声明类似C语言数组的声明,请不要混淆
  • Python中数组的声明需要import array包,使用较少,通常在数值运算中使用类似的np.array
  • c语言中没有集合的概念,c++中使用set和unordered_set来表示集合,c++11中引入了unordered_map和unordered_set,可以用来表示集合。c++中的集合运算。