找个AI,搜索一下python的特点,最好找个熟悉的语言做对比:
pip install uvhttps://www.python.org/
从官网下载安装包安装即可,自定义安装注意勾选环境变量
# 查看python是否安装完成
python -V
# 查看pip是否安装成功
pip -V
# 安装包管理工具uv
pip install uv
# 更新uv
pip install --upgrade uv
运行uv -h可以看到
Usage: uv.exe [OPTIONS] <COMMAND>
Commands:
auth Manage authentication
run Run a command or script
init Create a new project
add Add dependencies to the project
remove Remove dependencies from the project
version Read or update the project's version
sync Update the project's environment
lock Update the project's lockfile
export Export the project's lockfile to an alternate format
tree Display the project's dependency tree
format Format Python code in the project
tool Run and install commands provided by Python packages
python Manage Python versions and installations
pip Manage Python packages with a pip-compatible interface
venv Create a virtual environment
build Build Python packages into source distributions and wheels
publish Upload distributions to an index
cache Manage uv's cache
self Manage the uv executable
help Display documentation for a command
翻译一下
auth | |
run | |
init | |
add | |
remove | |
version | |
sync | |
lock | |
export | requirements.txt) |
tree | |
format | |
tool | |
python | |
pip | |
venv | |
build | |
publish | |
cache | |
self | |
help |
学习子命令使用uv export --help,子命令不在叙述
接下来新建一个项目开始学习语法:uv init my-proj
项目结构如下:
├── .gitignore
├── .python-version
├── main.py # 程序入口
├── pyproject.toml # uv配置文件
└── README.md
运行uv run main.py,运行后会生成uv.lock 和 自动创建虚拟环境。
官网找找文档:https://docs.python.org/zh-cn/3/tutorial/index.html
打开之后,醒目的提示:
小技巧:本教程被设计为针对新入门 Python 语言的 程序员,而不是新入门编程的 初学者。
正好合适,开始
以#开头
无需声明,直接使用v=1,结尾不需要分号;,没有大括号{}
# 同时初始化多个变量
a, b = 1, 2
可以用单引号或者双引号,多行使用三重单引号或双引号,和并可以用+
# 字符串拼接
v = 'hello'+'world'
# 字符串索引访问
v[0] # 'h',也支持负数,-1是最后一个字符
# 字符串切片
v[:2] # 'he'
v[2:5] # 'llo'
# 内置len()函数返回字符串长度
len(v) # 10
l = [0,1,2]
# 索引访问
l[0] # 0
l2 = l[0:] # [0,1,2]返回一个新的列表
# 合并
l3 = l + l2 # [0,1,2,0,1,2]返回一个新的列表
# 追加
l.append(3)
# 引用
l4 = l # 改变l4,l也会变
# while
a, b = 0, 1
while a < 1000:
print(a, end=',') # 可以在每个元素后面加上,
a, b = b, a+b
# if
a = int(input('请输入一个数字'))
if a < 0:
print('a < 0')
elif x == 0:
print('a = 0')
else
print('a > 0')
# for
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
# range,只有在迭代时候才会返回列表,正常不会有列表,节省空间
print(range(10)) # range(0, 10)
for i in range(5):
print(i)
# match case,类似Rust中的match
# point 是一个 (x, y) 元组
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")
# 可以包含默认值,有默认值的参数是选填的,如果有多选填,可以使用参数名=值传值
def oushu(n, b=False):
if(b):
n=n+1
for i in range(n):
if i % 2 == 0:
print(i)
oushu(10)
oushu(10, True)
官方文档:https://docs.python.org/zh-cn/3/tutorial/datastructures.html
技巧:
items()提取键值for k, v in dicts.items():
print(k, v)
enumerate()同时提取索引和值for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
zip()一一匹配 questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
and or not文档写了太多,总结一下常用的方式:
import demo__init__.py文件可以是空的,直接用from demo import testyear = 2016
event = 'Referendum'
f'Results of the {year} {event}'
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
f = open('workfile', 'r', encoding="utf-8")
read_data = f.read()
f.close()
# 使用with会自动关闭文件,发生异常也会关闭
with open('workfile', encoding="utf-8") as f:
for line in f:
print(line, end='')
with open('workfile','w', encoding="utf-8") as f:
f.write('hello\n')
import json
x = [1, 'simple', 'list']
json.dumps(x)
try:
# 可能出错的代码
except SomeException:
# 捕获并处理异常
else:
# 仅在 try 中没有发生异常时执行
finally:
# 无论是否有异常,总是执行
raise # 相当于throw,后面跟异常类或者异常对象都可以,或者在except中,后面不加东西直接抛出
#class MyClass(BaseClassName,Base2): 继承且允许多重继承
class MyClass:
"""一个简单的示例类"""
arr = ['1','2'] # 相当于静态变量,只有一份,所有对象共享
def __init__(self, name): #构造函数
self.name = name # 相当于实例变量
def f(self):
return 'hello world'+self.name
mc = MyClass('不吃西红柿')
print(mc.arr)
print(mc.f())
捡了文档中常用的,不常用的等用的时候查就行
# 操作系统
import os
os.getcwd()
os.system('mkdir test')
# 文件/目录 管理
import shutil
shutil.copyfile('data.db','other.db')
shutil.move('/opt/test','test')
# 文件通配符
import glob
glob.glob('*.py')
# sys
import sys
print(sys.argv)
sys.stderr.write('Error')
sys.stdout.write('out')
# 正则表达式
import re
re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
# 数学
import math
math.cos(math.pi / 4)
# 随机
import random
random.random() # [0.0, 1.0) 区间的随机浮点数
# 访问互联网
from urllib.request import urlopen
with urlopen('https://docs.python.org/3/') as response:
for line in response:
line = line.decode() # 将bytes转换str
if 'updated' in line:
print(line.rstrip())
# 日期和时间
from datetime import date
now = date.today()
print(now.strftime("%y-%m-%d"))
birthday = date(2019,10,20)
age = now - birthday
print(age.days)
# 多线程
import threading, zipfile
class AsyncZip(threading.Thread):
def __init__(self, infile, outfile):
threading.Thread.__init__(self)
self.infile = infile
self.outfile = outfile
def run(self):
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
f.write(self.infile)
f.close()
print('Finished background zip of:', self.infile)
background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')
background.join() # 等待任务结束
print('Main program waited until background was done.')
# 日志
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file not found')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
咱就不看了,uv工具已经自动管理虚拟环境了,有想了解的自己去看文档吧
python的官方文档还是非常友好的
现在已经是Vibe Coding的时代了,能看懂代码就好。