Python的50个常识问题解答

发布时间:2024年01月22日

一、说明

?? 关于python的一些大致理解,初学者可以参考本文做一个直观理解;其中也不乏有趣事实。

二、python大世界

??
Python于1991年首次发布,由Guido van Rossum创建。
“python”这个名字来源于英国喜剧团体Monty Python,而不是蛇。
Python 是一种解释型语言,这意味着它在运行之前不需要编译。
Python是一种高级语言,这意味着与C或汇编等低级语言相比,它更容易阅读和编写。
Python 是一种动态类型语言,这意味着在声明变量时不需要指定变量的类型。
Python是一种面向对象的语言,这意味着它基于对象和类的概念。
Python 拥有一个庞大而活跃的社区,有大量的库和框架可供使用。
Python被许多大公司使用,包括Google,NASA和Instagram。
Python 通常用于 Web 开发、数据分析和科学计算。
Python非常强调可读性和简单性,强调使用空格来构建代码。
Python的语法类似于英语,这使其成为初学者的绝佳语言。
Python有一个叫做“Python的禅宗”的哲学,可以通过在解释器中键入“import this”来访问。
Python有一个名为“列表理解”的功能,它允许你使用一行代码创建一个列表。
Python有一个名为“生成器”的功能,它允许你创建一个迭代器来动态生成值,而不是预先创建一个完整的列表。
Python有一个名为“itertools”的模块,其中包含一系列用于处理迭代器的函数。
Python 有一个名为“装饰器”的功能,它允许您修改函数的行为,而无需更改函数内部的代码。
Python有一个名为“lambda函数”的功能,它允许你即时创建小型匿名函数。
Python有一个名为“functools”的内置模块,其中包含一系列用于处理函数的函数。
Python有一个名为“集合”的模块,其中包含用于处理数据的专用数据类型。
Python有一个名为“typeping”的模块,它允许你在代码中指定变量的类型,以添加类型检查。
Python有一个名为“asyncio”的功能,它允许你使用async/await语法编写异步代码。
Python有一个名为“asyncio”的模块,其中包含一系列用于处理异步代码的工具。
Python有一个名为“aiohttp”的模块,它允许你发出异步HTTP请求。
Python有一个名为“多处理”的模块,它允许你编写可以跨多个CPU内核并发运行的代码。
Python有一个名为“线程”的模块,它允许你编写可以使用线程并发运行的代码。
Python有一个名为“concurrent.futures”的模块,它允许你使用线程或进程池编写并发代码。
Python有一个名为“contextlib”的模块,其中包含一系列用于使用上下文管理器的函数。
Python有一个名为“timeit”的模块,它允许你测量小代码的性能。
Python 有一个名为“profile”的模块,它允许您分析代码的性能以确定需要优化的区域。
Python有一个名为“unittest”的模块,它允许你为代码编写自动测试。这对于确保代码正确且按预期工作非常有用,尤其是在进行更改或更新时。
Python有一个名为“docstrings”的功能,它允许你直接在源代码中包含代码的文档。
Python 有一个名为“pdb”的内置模块,它允许您使用命令行调试器来调试代码。
Python 有一个名为“traceback”的内置模块,它允许您检索异常的回溯并检查调用堆栈。
Python 有一个名为“time”的内置模块,它允许您处理时间和日期数据。
Python 有一个名为“datetime”的内置模块,它提供了处理时间和日期数据的更高级功能。
Python 有一个名为“calendar”的内置模块,它允许您使用日历并执行与日历相关的操作。
Python 有一个名为“random”的内置模块,它允许您生成随机数并执行随机选择。
Python 有一个名为“math”的内置模块,它提供数学函数和常量。
Python 有一个名为“cmath”的内置模块,它提供了用于处理复数的数学函数。
Python 有一个名为“statistics”的内置模块,提供统计功能和工具。
Python有一个名为“os”的内置模块,它提供与操作系统交互的功能。
Python 有一个名为“sys”的内置模块,它提供对系统特定参数和函数的访问。
Python 有一个名为“subprocess”的内置模块,它允许您生成新进程并与它们交互。
Python有一个名为“tempfile”的内置模块,它允许你创建临时文件和目录。
Python 有一个名为“shutil”的内置模块,它提供了处理文件和目录的功能,例如复制、移动和删除。
Python有一个名为“glob”的内置模块,它允许你找到与特定模式匹配的文件和目录。
Python有一个名为“zipfile”的内置模块,它允许你处理ZIP存档文件。
Python有一个名为“tarfile”的内置模块,它允许你处理TAR存档文件。
Python有一个名为“webbrowser”的内置模块,它允许你在Web浏览器中打开URL。
Python有一个名为“urllib”的内置模块,它允许你发送HTTP请求并使用URL。

三、一些初学者示例

?? 下面是一些示例来说明其中一些功能:
1)列表理解:

# Create a list of numbers from 0 to 9
numbers = [i for i in range(10)]
print(numbers)
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2)生成偶数

# Create a list of even numbers from 0 to 9
even_numbers = [i for i in range(10) if i % 2 == 0]
print(even_numbers)
# Output: [0, 2, 4, 6, 8]

3)生成器

# Create a generator that generates numbers from 0 to 9
def generate_numbers():
    for i in range(10):
        yield i

# Create a generator object
numbers = generate_numbers()

# Iterate over the generator
for number in numbers:
    print(number)
# Output: 0 1 2 3 4 5 6 7 8 9

4)装饰器

# Create a decorator that adds a greeting to a function
def greet(func):
    def wrapper():
        print("Hello!")
        func()
    return wrapper

5)定义函数

# Define a function
def say_hi():
    print("Hi!")
# Use the decorator to modify the function
greeted_hi = greet(say_hi)

# Call the modified function
greeted_hi()
# Output: Hello! Hi!

6)代理函数

# Create a lambda function that adds two numbers
add = lambda x, y: x + y

# Use the lambda function
result = add(3, 4)
print(result)
# Output: 7

7)同步函数

import asyncio

# Define an async function
async def fetch_data():
    # Perform some asynchronous tasks
    await asyncio.sleep(1)
    return "Data fetched!"

# Use the async function
result = await fetch_data()
print(result)
# Output: Data fetched!
import aiohttp
import asyncio


# Define an async function
async def fetch_data():
    # Use aiohttp to make an async HTTP request
    async with aiohttp.ClientSession() as session:
        async with session.get('https://www.example.com/') as resp:
            return await resp.text()

# Use the async function
result = await fetch_data()
print(result)

8)多进程

import multiprocessing

# Define a function to be run in a separate process
def worker(num):
    return num * 2

# Create a pool of processes
with multiprocessing.Pool(4) as p:
    # Use the map function to apply the worker function to a list of numbers
    results = p.map(worker, [1, 2, 3, 4])
    print(results)
# Output: [2, 4, 6, 8]

9)多线程

import threading

# Define a function to be run in a separate thread
def worker(num):
    return num * 2

# Create a thread
t = threading.Thread(target=worker, args=(2,))

# Start the thread
t.start()

# Wait for the thread to finish
t.join()

# Print the result of the worker function
print(t.result)
# Output: 4

import concurrent.futures
# Define a function to be run in a separate thread or process
def worker(num):
    return num * 2
# Create a thread or process pool
with concurrent.futures.ThreadPoolExecutor() as executor:
    # Use the map function to apply the worker function to a list of numbers
    results = executor.map(worker, [1, 2, 3, 4])
    print(list(results))
# Output: [2, 4, 6, 8]

10)上下文管理

import contextlib

# Define a context manager that opens and closes a file
@contextlib.contextmanager
def open_file(path):
    f = open(path, 'w')
    yield f
    f.close()
# Use the context manager to open and write to a file
with open_file('test.txt') as f:
    f.write('Hello, world!')

11)时间和定时器

import timeit

# Measure the time it takes to run a function
result = timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
print(result)
# Output: 0.21759009399414062

12)使用配置文件

import profile

def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

# Run the code through the profiler
profile.run('fibonacci(20)')

13)随机场合

import random

# Generate a random number between 0 and 1
num = random.random()
print(num)

# Generate a random integer between 0 and 10
num = random.randint(0, 10)
print(num)

# Choose a random element from a list
items = [1, 2, 3, 4, 5]
item = random.choice(items)
print(item)

# Shuffle a list in place
random.shuffle(items)
print(items)

# Select k random elements from a list
selected = random.sample(items, k=3)
print(selected)

13)数学库

import math

# Calculate the square root of a number
result = math.sqrt(16)
print(result)

# Calculate the sine of an angle
result = math.sin(math.pi / 2)
print(result)

# Access mathematical constants
print(math.pi)
print(math.e)


import cmath

# Calculate the square root of a negative number (returns a complex number)
result = cmath.sqrt(-1)
print(result)

# Calculate the sine of an angle (returns a complex number)
result = cmath.sin(cmath.pi / 2)
print(result)

四、后记

?? 本文粗略介绍python的基础编程,和puthon语言的一些基本知识,供读者随手查找,但更多的技能还是学习专业文档。谢谢!

?

文章来源:https://blog.csdn.net/gongdiwudu/article/details/135734941
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。