Python必会的50个代码操作

liftword3个月前 (03-11)技术文章22

学习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)

相关文章

Python 内联 If 语句使用指南

Python 的内联 if 语句(也称为三元运算符)允许您在一行中编写条件表达式。让我们探索如何有效地使用它们,以及何时它们会使您的代码变得更好。基本内联 If 语法下面是基本模式:# Standar...

Python程序员必看3分钟掌握if语句10个神技,第5个99%的人不知道

同事因为写错一个if被开除?全网疯传的Python避坑指南,看完我连夜改了代码!一、新手必踩的3大天坑(附救命代码)技巧1:缩进踩坑事件if True: print("这样写必报错!") # 缺...

12-Python语法01-if语句

1-if语句1-1-概念if 语句用于基于特定条件执行代码块。它允许程序根据不同的条件做出决策,从而实现逻辑控制。这是编程中最基本的控制结构之一,广泛应用于各种场景中1-2-特点灵活性:可以根据一个或...

python入门-day4-条件语句

以下是基于你提供的信息,为“Day 4: 条件语句”设计的详细学习任务计划。这个任务适合编程初学者,帮助他们掌握条件语句的基本使用,并通过实践加深理解。Day 4: 条件语句学习目标:理解并掌握条件语...

Python 流程控制:条件与循环语句全解

在 Python 编程的世界里,流程控制是构建程序逻辑的关键,它能让程序根据不同的条件执行不同的操作,或者重复执行特定的代码块。今天,我们就来深入探讨 Python 中的条件语句(if-elif-el...

Python if else条件语句详解

前面我们看到的代码都是顺序执行的,也就是先执行第1条语句,然后是第2条、第3条……一直到最后一条语句,这称为顺序结构。但是对于很多情况,顺序结构的代码是远远不够的,比如一个程序限制了只能成年人使用,儿...