Python从入门到晋级代码30行

一、Python基础入门代码10行

打印Hello World!

print("Hello World!")

定义变量并打印出来```

```python
name = "Alice"
print("My name is", name)

判断语句if-else`

age = 22
if age < 18:
    print("You are too young.")
else:
    print("Welcome!")

循环语句for

for i in range(5):
    print("Number:", i)

列表List

fruits = ["apple", "banana", "cherry"]
print(fruits[1])

字典Dictionary

person = {
    
    "name": "Alice", "age": 22, "gender": "female"}
print(person["age"])

函数Function

def add_numbers(x, y):
    return x + y
result = add_numbers(3, 5)
print(result)

文件读写

file = open("example.txt", "w")
file.write("Hello World!")
file.close()

异常处理

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

导入模块

import math
result = math.sqrt(16)
print(result)

二、Python菜鸟提升代码10行

Lambda函数

square = lambda x: x**2
print(square(4))

列表推导式

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)

面向对象编程

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def greeting(self):
        print("Hello, my name is", self.name)
person = Person("Alice", 22)
person.greeting()

装饰器Decorator

def uppercase_decorator(func):
    def wrapper():
        result = func()
        return result.upper()
    return wrapper

@uppercase_decorator
def greeting():
    return "Hello World!"

print(greeting())

迭代器Iterator

numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))

生成器Generator

def fibonacci(n):
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a + b

for number in fibonacci(10):
    print(number)

静态方法staticmethod

class MyClass:
    @staticmethod
    def greeting():
        print("Hello World!")

MyClass.greeting()

上下文管理器with语句

with open("example.txt", "r") as file:
    for line in file:
        print(line)

多线程Threading

import threading

def print_numbers():
    for i in range(10):
        print(i)

def print_letters():
    for letter in ["a", "b", "c", "d", "e"]:
        print(letter)

thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()

正则表达式Regular Expression

import re

text = "The cat in the hat"
pattern = "cat"
result = re.findall(pattern, text)
print(result)

三、Python基础晋级代码10行

列表和字典的高级操作

fruits = ["apple", "banana", "cherry"]
fruit_dict = {
    
    fruit: len(fruit) for fruit in fruits}
print(fruit_dict)

高级字符串操作

text = "    Hello World!     "
print(text.strip())
print(text.replace("World", "Universe"))

匿名函数和map操作

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)

列表排序和筛选

numbers = [5, 2, 7, 1, 9]
filtered = list(filter(lambda x: x < 6, numbers))
sorted_numbers = sorted(numbers)
print(filtered)
print(sorted_numbers)

文件读写的高级操作

with open("example.txt", "r") as file:
    text = file.read()
    lines = text.split("\n")
    non_empty = list(filter(lambda x: x != "", lines))
    print(non_empty)

时间和日期操作

import datetime

today = datetime.date.today()
print(today)
one_day = datetime.timedelta(days=1)
yesterday = today - one_day
print(yesterday)

面向对象的高级应用

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age
    @property
    def name(self):
        return self._name
    @property
    def age(self):
        return self._age
    @age.setter
    def age(self, value):
        if isinstance(value, int) and value > 0:
            self._age = value
        else:
            raise ValueError("Invalid age value.")

person = Person("Alice", 22)
print(person.name)
print(person.age)
person.age = 23
print(person.age)

列表解包和多重赋值

fruits = ["apple", "banana", "cherry"]
first, *rest = fruits
a, b, c = fruits
print(first)
print(rest)
print(a)
print(b)
print(c)

协程Coroutine

def coroutine():
    while True:
        x = yield
        print("Received:", x)

coro = coroutine()
next(coro)
coro.send("Hello World!")

并发编程和多进程Multiprocessing

from multiprocessing import Process

def square(numbers):
    result = [x**2 for x in numbers]
    print(result)

numbers1 = [1, 2, 3, 4, 5]
numbers2 = [6, 7, 8, 9, 10]

process1 = Process(target=square, args=(numbers1,))
process2 = Process(target=square, args=(numbers2,))

process1.start()
process2.start()

process1.join()
process2.join()

猜你喜欢

转载自blog.csdn.net/maomaodaren1/article/details/129488542