Python必会的50个代码操作
off999 2025-05-16 15:35 19 浏览 0 评论
学习Python时,掌握一些常用的程序操作非常重要。以下是50个Python必会的程序操作,主要包括基础语法、数据结构、函数和文件操作等。
1. Hello World
print("Hello, World!")
2. 注释
# 这是单行注释
'''
这是多行注释
'''
3. 变量赋值
x = 10
y = 20.5
name = "Python"
4. 类型转换
x = int(10.5) # 转为整数
y = float("20.5") # 转为浮点数
5. 输入输出
name = input("Enter your name: ")
print("Hello", name)
6. 条件语句
if x > y:
print("x is greater")
elif x < y:
print("y is greater")
else:
print("x and y are equal")
7. 循环
for循环
for i in range(5):
print(i)
while循环
i = 0
while i < 5:
print(i)
i += 1
8. 列表操作
lst = [1, 2, 3, 4]
lst.append(5)
lst.remove(3)
lst[0] = 10
9. 字典操作
dic = {"name": "Alice", "age": 25}
dic["age"] = 26
dic["city"] = "New York"
10. 元组操作
tup = (1, 2, 3)
print(tup[0])
11. 集合操作
s = {1, 2, 3}
s.add(4)
s.remove(2)
12. 函数定义
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
13. 返回值
def add(x, y):
return x + y
print(add(3, 4))
14. 匿名函数(Lambda)
square = lambda x: x**2
print(square(5))
15. 递归
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
16. 异常处理
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
17.文件操作
读取文件
with open("file.txt", "r") as file:
content = file.read()
print(content)
写入文件
with open("file.txt", "w") as file:
file.write("Hello, World!")
18. 模块导入
import math
print(math.sqrt(16))
19. 类和对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}.")
person = Person("Alice", 25)
person.greet()
20. 继承
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def greet(self):
super().greet()
print(f"I'm in grade {self.grade}.")
student = Student("Bob", 20, "A")
student.greet()
21. 列表推导式
squares = [x**2 for x in range(10)]
22. 字典推导式
square_dict = {x: x**2 for x in range(5)}
23. 集合推导式
unique_squares = {x**2 for x in range(5)}
24. 生成器
def generate_numbers(n):
for i in range(n):
yield i
gen = generate_numbers(5)
for num in gen:
print(num)
25. 正则表达式
import re
pattern = r'\d+'
text = "There are 123 apples"
result = re.findall(pattern, text)
print(result)
26. 日期和时间
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
27. 排序
lst = [5, 3, 8, 6]
lst.sort() # 升序
lst.sort(reverse=True) # 降序
28. 枚举
lst = ["a", "b", "c"]
for index, value in enumerate(lst):
print(index, value)
29. zip函数
lst1 = [1, 2, 3]
lst2 = ["a", "b", "c"]
zipped = zip(lst1, lst2)
for item in zipped:
print(item)
30. all()和any()
lst = [True, True, False]
print(all(lst)) # False
print(any(lst)) # True
31. 切片
lst = [0, 1, 2, 3, 4]
print(lst[1:4]) # 输出 [1, 2, 3]
32. 列表拼接
lst1 = [1, 2]
lst2 = [3, 4]
lst3 = lst1 + lst2
33. 内存管理(del)
lst = [1, 2, 3]
del lst[1] # 删除索引1的元素
34. 函数式编程(map, filter, reduce)
from functools import reduce
lst = [1, 2, 3, 4]
result = map(lambda x: x**2, lst) # 平方每个元素
result = filter(lambda x: x % 2 == 0, lst) # 过滤偶数
result = reduce(lambda x, y: x + y, lst) # 求和
35. 列表展开
lst = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in lst for item in sublist]
36. 接口
from abc import ABC, abstractmethod
class MyInterface(ABC):
@abstractmethod
def do_something(self):
pass
37. 用from import方式导入部分模块
from math import pi
print(pi)
38. 命令行参数
import sys
print(sys.argv) # 获取命令行参数
39. 生成随机数
import random
print(random.randint(1, 100)) # 生成1到100的随机整数
40. 计时器(time模块)
import time
start_time = time.time()
time.sleep(2) # 等待2秒
end_time = time.time()
print(f"Duration: {end_time - start_time} seconds")
41. 进程与线程
from threading import Thread
def print_hello():
print("Hello from thread")
t = Thread(target=print_hello)
t.start()
42. 环境变量
import os
os.environ["MY_VAR"] = "some_value"
print(os.environ["MY_VAR"])
43. pip安装包
pip install package_name
44. 虚拟环境
python -m venv myenv
source myenv/bin/activate # 激活
deactivate # 退出
45. 命令行解析(argparse)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
print(f"Hello {args.name}")
46. JSON解析
import json
data = '{"name": "Alice", "age": 25}'
obj = json.loads(data)
print(obj["name"])
47. 多线程并发
from concurrent.futures import ThreadPoolExecutor
def task(x):
return x * 2
with ThreadPoolExecutor() as executor:
results = executor.map(task, [1, 2, 3])
print(list(results))
48. 装饰器
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def greet():
print("Hello!")
greet()
49. 文件遍历
import os
for file_name in os.listdir("my_dir"):
print(file_name)
50. 上下文管理器(with语句)
with open("file.txt", "r") as file:
content = file.read()
print(content)
相关推荐
- pip的使用及配置_pip怎么配置
-
要使用python必须要学会使用pip,pip的全称:packageinstallerforpython,也就是Python包管理工具,主要是对python的第三方库进行安装、更新、卸载等操作,...
- Anaconda下安装pytorch_anaconda下安装tensorflow
-
之前的文章介绍了tensorflow-gpu的安装方法,也介绍了许多基本的工具与使用方法,具体可以看Ubuntu快速安装tensorflow2.4的gpu版本。pytorch也是一个十分流行的机器学...
- Centos 7 64位安装 python3的教程
-
wgethttps://www.python.org/ftp/python/3.10.13/Python-3.10.13.tgz#下载指定版本软件安装包tar-xzfPython-3.10.1...
- 如何安装 pip 管理工具_pip安装详细步骤
-
如何安装pip管理工具方法一:yum方式安装Centos安装python3和python3-devel开发包>#yuminstallgcclibffi-develpy...
- Python入门——从开发环境搭建到hello world
-
一、Python解释器安装1、在windows下步骤1、下载安装包https://www.python.org/downloads/打开后选择【Downloads】->【Windows】小编是一...
- 生产环境中使用的十大 Python 设计模式
-
在软件开发的浩瀚世界中,设计模式如同指引方向的灯塔,为我们构建稳定、高效且易于维护的系统提供了经过验证的解决方案。对于Python开发者而言,理解和掌握这些模式,更是提升代码质量、加速开发进程的关...
- 如何创建和管理Python虚拟环境_python怎么创建虚拟环境
-
在Python开发中,虚拟环境是隔离项目依赖的关键工具。下面介绍创建和管理Python虚拟环境的主流方法。一、内置工具:venv(Python3.3+推荐)venv是Python标准...
- 初学者入门Python的第一步——环境搭建
-
Python如今成为零基础编程爱好者的首选学习语言,这和Python语言自身的强大功能和简单易学是分不开的。今天千锋武汉Python培训小编将带领Python零基础的初学者完成入门的第一步——环境搭建...
- 全网最简我的世界Minecraft搭建Python编程环境
-
这篇文章将给大家介绍一种在我的世界minecraft里搭建Python编程开发环境的操作方法。目前看起来应该是全网最简单的方法。搭建完成后,马上就可以利用python代码在我的世界自动创建很多有意思的...
- Python开发中的虚拟环境管理_python3虚拟环境
-
Python开发中,虚拟环境管理帮助隔离项目依赖,避免不同项目之间的依赖冲突。虚拟环境的作用隔离依赖:不同项目可能需要不同版本的库,虚拟环境可以为每个项目创建独立的环境。避免全局污染:全局安装的库可...
- Python内置zipfile模块:操作 ZIP 归档文件详解
-
一、知识导图二、知识讲解(一)zipfile模块概述zipfile模块是Python内置的用于操作ZIP归档文件的模块。它提供了创建、读取、写入、添加及列出ZIP文件的功能。(二)ZipFile类1....
- Python内置模块pydoc :文档生成器和在线帮助系统详解
-
一、引言在Python开发中,良好的文档是提高代码可读性和可维护性的关键。pydoc是Python自带的一个强大的文档生成器和在线帮助系统,它可以根据Python模块自动生成文档,并支持多种输出格式...
- Python sys模块使用教程_python system模块
-
1.知识导图2.sys模块概述2.1模块定义与作用sys模块是Python标准库中的一个内置模块,提供了与Python解释器及其环境交互的接口。它包含了许多与系统相关的变量和函数,可以用来控制P...
- Python Logging 模块完全解读_python logging详解
-
私信我,回复:学习,获取免费学习资源包。Python中的logging模块可以让你跟踪代码运行时的事件,当程序崩溃时可以查看日志并且发现是什么引发了错误。Log信息有内置的层级——调试(deb...
- 软件测试|Python logging模块怎么使用,你会了吗?
-
Pythonlogging模块使用在开发和维护Python应用程序时,日志记录是一项非常重要的任务。Python提供了内置的logging模块,它可以帮助我们方便地记录应用程序的运行时信息、错误和调...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)