一篇文章教你入门Python


💝💝💝欢迎莅临我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。


基础语法

变量和数据类型

python 复制代码
x = 10  # 整数
name = "Kimi"  # 字符串
is_active = True  # 布尔值

控制结构

python 复制代码
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

for i in range(5):
    print(i)

while x < 10:
    x += 1

函数

python 复制代码
def greet(name):
    print(f"Hello, {name}!")

greet("Kimi")

数据结构

列表

python 复制代码
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)

字典

python 复制代码
person = {"name": "Kimi", "age": 25}
print(person["name"])

集合

python 复制代码
numbers = {1, 2, 3, 4, 5}
unique_numbers = numbers.union({5, 6, 7})
print(unique_numbers)

元组

python 复制代码
coordinates = (10.0, 20.0)
print(coordinates)

面向对象编程

类和对象

python 复制代码
class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

my_car = Car("Tesla", "Model S")
print(my_car.brand)

继承

python 复制代码
class ElectricCar(Car):
    def __init__(self, brand, model, battery_size):
        super().__init__(brand, model)
        self.battery_size = battery_size

my_electric_car = ElectricCar("Tesla", "Model S", 100)

文件和异常处理

文件操作

python 复制代码
with open('file.txt', 'w') as file:
    file.write("Hello, world!")

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

异常处理

python 复制代码
try:
    x = int(input("Enter a number: "))
    y = 10 / x
except ValueError:
    print("Invalid input")
except ZeroDivisionError:
    print("Cannot divide by zero")

模块和包

导入模块

python 复制代码
import math
print(math.sqrt(16))

创建和使用包

python 复制代码
# 在同一目录下创建一个名为my_package的文件夹,并在其中创建一个__init__.py文件和一个module.py文件
# module.py中包含以下内容:
def hello():
    print("Hello from module")

# 在其他Python文件中导入模块
from my_package.module import hello
hello()

网络编程

使用socket

python 复制代码
import socket

s = socket.socket()
host = 'localhost'
port = 12345

s.bind((host, port))
s.listen(5)
conn, addr = s.accept()
print('Connected by', addr)

数据库操作

使用SQLite

python 复制代码
import sqlite3

conn = sqlite3.connect('example.db')
c = conn.cursor()

## 创建表
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text,
            qty real, price real)''')

## 插入一条记录
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

## 查询表
c.execute('SELECT * FROM stocks')
print(c.fetchall())

conn.commit()
conn.close()

原文:https://mp.weixin.qq.com/s/WrjlH84dC9njta-wjIJZ1Q


🔥🔥🔥道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙

|---------------------------|
| 💖The End💖点点关注,收藏不迷路💖 |

相关推荐
用户83562907805114 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户83562907805114 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生1 天前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师1 天前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码1 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf1 天前
FastAPI 如何连接 MySQL
后端·python
apocelipes2 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780512 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent2 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python