python基本知识

发布于:2024-09-18 ⋅ 阅读:(116) ⋅ 点赞:(0)

. 基本语法

  • 注释:用 # 开始单行注释。
  • 缩进:Python 使用缩进表示代码块,通常为 4 个空格。
  • 变量:可以直接赋值,不需要声明类型。
     

    python

    复制代码

    x = 10 name = "Alice"

2. 数据类型

  • 基本数据类型
    • int (整数)
    • float (浮点数)
    • str (字符串)
    • bool (布尔值,TrueFalse)
     

    python

    复制代码

    age = 25 # int price = 19.99 # float name = "John" # str is_valid = True # bool

3. 数据结构

  • 列表 (List):有序可变的元素集合,使用方括号 []
     

    python

    fruits = ["apple", "banana", "cherry"]

  • 元组 (Tuple):有序不可变的元素集合,使用圆括号 ()
     

    python

    point = (4, 5)

  • 字典 (Dictionary):键值对的集合,使用大括号 {}
     

    python

    person = {"name": "Alice", "age": 30}

  • 集合 (Set):无序、不重复的元素集合,使用大括号 {}
     

    python

    numbers = {1, 2, 3}

4. 条件判断

使用 ifelifelse 进行条件判断:


python

x = 10 if x > 5: print("x is greater than 5") elif x == 5: print("x is 5") else: print("x is less than 5")

5. 循环

  • for 循环:用于遍历序列(如列表、字符串等)。
     

    python

    for fruit in fruits: print(fruit)

  • while 循环:当条件为真时重复执行。
     

    python

    i = 0 while i < 5: print(i) i += 1

6. 函数

使用 def 关键字定义函数:


python

def greet(name): return f"Hello, {name}" message = greet("Alice") print(message)

7. 类与对象

Python 是面向对象的语言,支持类的定义和对象的创建:


python

class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name}") p = Person("Bob", 25) p.greet()

8. 文件操作

  • 读取文件:
     

    python

    with open("file.txt", "r") as file: content = file.read() print(content)

  • 写入文件:
     

    python

    with open("file.txt", "w") as file: file.write("Hello, World!")

9. 异常处理

使用 tryexcept 处理异常:


python

try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")

10. 常用库

  • math:数学函数库。
     

    python

    import math print(math.sqrt(16)) # 计算平方根

  • random:生成随机数。
     

    python

    import random print(random.randint(1, 10)) # 随机整数