Python基础知识点

Python 基础知识点

目录

  1. 简介
  2. 基本语法
  3. 控制结构
  4. 函数
  5. 数据结构
  6. 面向对象编程
  7. 模块和包
  8. 异常处理
  9. 文件操作
  10. 常用库

简介

Python 是一种高级编程语言,以其简洁、易读、强大而受到广泛欢迎。它支持多种编程范式,包括面向对象编程、过程式编程和函数式编程。

基本语法

变量和数据类型

Python 支持多种数据类型,如整数(int)、浮点数(float)、字符串(str)、布尔值(bool)等。

x = 10  # 整数
y = 3.14  # 浮点数
name = "Alice"  # 字符串
is_valid = True  # 布尔值

运算符

Python 提供了丰富的运算符,包括算术运算符、比较运算符、逻辑运算符等。

# 算术运算符
a = 10 + 5  # 加法
b = 10 - 5  # 减法
c = 10 * 5  # 乘法
d = 10 / 5  # 除法
e = 10 % 3  # 取余
f = 10 ** 2  # 幂运算

# 比较运算符
print(10 > 5)  # True
print(10 == 5)  # False

# 逻辑运算符
print(True and False)  # False
print(True or False)  # True
print(not True)  # False

控制结构

条件语句

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

x = 10
if x > 5:
    print("x 大于 5")
elif x == 5:
    print("x 等于 5")
else:
    print("x 小于 5")

循环语句

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

# for 循环
for i in range(5):
    print(i)

# while 循环
count = 0
while count < 5:
    print(count)
    count += 1

函数

定义函数

函数是一段可以重复使用的代码块。

def greet(name):
    print(f"Hello, {name}")

greet("Alice")

参数和返回值

函数可以接受参数并返回值。

def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # 8

数据结构

列表

列表是一个有序的可变集合。

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # apple
fruits.append("date")
print(fruits)  # ["apple", "banana", "cherry", "date"]

字典

字典是一个无序的键值对集合。

person = {"name": "Alice", "age": 25}
print(person["name"])  # Alice
person["age"] = 26
print(person)  # {"name": "Alice", "age": 26}

元组

元组是一个有序的不可变集合。

colors = ("red", "green", "blue")
print(colors[1])  # green

集合

集合是一个无序的不重复元素集合。

unique_numbers = {1, 2, 3, 4, 4, 5}
print(unique_numbers)  # {1, 2, 3, 4, 5}

面向对象编程

类和对象

类是对象的蓝图,对象是类的实例。

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} is barking")

my_dog = Dog("Buddy")
my_dog.bark()  # Buddy is barking

继承

继承用于创建一个类,该类可以继承另一个类的属性和方法。

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError

class Cat(Animal):
    def speak(self):
        return "Meow"

my_cat = Cat("Kitty")
print(my_cat.speak())  # Meow

多态

多态允许不同的类以相同的接口进行交互。

class Bird(Animal):
    def speak(self):
        return "Chirp"

animals = [Cat("Kitty"), Bird("Tweety")]
for animal in animals:
    print(animal.speak())  # Meow, Chirp

模块和包

导入模块

模块是一个包含 Python 代码的文件,可以导入到其他代码中使用。

import math
print(math.sqrt(16))  # 4.0

创建包

包是一个包含多个模块的文件夹。文件夹下必须有一个 __init__.py 文件。

mypackage/
    __init__.py
    module1.py
    module2.py

异常处理

异常处理用于处理程序运行时的错误。

try:
    result = 10 / 0
except ZeroDivisionError:
    print("除以零错误")
finally:
    print("无论是否有异常,都会执行")

文件操作

Python 提供了内置函数用于文件操作。

# 读取文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

# 写入文件
with open("example.txt", "w") as file:
    file.write("Hello, World!")

常用库

NumPy

NumPy 是用于科学计算的库,提供了高性能的多维数组对象和相关函数。

import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr * 2)  # [2 4 6 8]

Pandas

Pandas 是用于数据操作和分析的库,提供了 DataFrame 数据结构。

import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)

Matplotlib

Matplotlib 是用于绘制数据可视化图表的库。

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值