Python 是一种简洁、易读且功能强大的编程语言,广泛应用于 Web 开发、数据分析、人工智能、自动化脚本等领域。以下是 Python 的基础语法要点:
Python 程序不需要显式的入口点(如 main()
函数),代码从上到下逐行执行。
pythonprint("Hello, World!") # 输出内容到控制台
提示
python程序使用 #
作为注释符号
Python 支持多种内置数据类型:
int
float
str
bool
list
tuple
dict
set
python# 示例
age = 25 # int
height = 5.7 # float
name = "Alice" # str
is_student = True # bool
numbers = [1, 2, 3] # list
coordinates = (4, 5) # tuple
person = {"name": "Bob", "age": 30} # dict
unique_numbers = {1, 2, 3, 3} # set
使用 input()
获取用户输入,使用 print()
输出内容。
pythonname = input("Enter your name: ")
print(f"Hello, {name}!")
pythonif age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
for
循环:pythonfor i in range(5): # 遍历 0 到 4
print(i)
while
循环:pythoncount = 0
while count < 5:
print(count)
count += 1
使用 def
关键字定义函数。
pythondef greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message) # 输出: Hello, Alice!
pythondef greet(name="Guest"):
return f"Hello, {name}!"
print(greet()) # 输出: Hello, Guest!
print(greet("Alice")) # 输出: Hello, Alice!
列表是 Python 中最常用的数据结构之一。
pythonfruits = ["apple", "banana", "cherry"]
pythonfruits.append("orange") # 在末尾添加
fruits.insert(1, "grape") # 在索引 1 处插入
pythonfruits.remove("banana") # 删除指定值
del fruits[0] # 删除索引为 0 的元素
pythonfor fruit in fruits:
print(fruit)
字典是以键值对形式存储数据的结构。
pythonperson = {"name": "Alice", "age": 25}
pythonprint(person["name"]) # 输出: Alice
person["age"] = 26 # 修改年龄
pythonfor key, value in person.items():
print(f"{key}: {value}")
Python 提供了简单的方式处理文件。
pythonwith open("example.txt", "r") as file:
content = file.read()
print(content)
pythonwith open("example.txt", "w") as file:
file.write("Hello, File!")
使用 try...except
捕获和处理异常。
pythontry:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution complete.")
Python 支持面向对象编程(OOP),可以通过类和对象实现封装、继承和多态。
pythonclass Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
# 创建对象
alice = Person("Alice", 25)
alice.introduce() # 输出: My name is Alice and I am 25 years old.
pythonclass Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def study(self):
print(f"{self.name} is studying in grade {self.grade}.")
student = Student("Bob", 15, 10)
student.introduce() # 输出: My name is Bob and I am 15 years old.
student.study() # 输出: Bob is studying in grade 10.
模块是一个包含 Python 代码的文件,而包是包含多个模块的目录。
pythonimport math
print(math.sqrt(16)) # 输出: 4.0
pythonfrom math import sqrt
print(sqrt(16)) # 输出: 4.0
mymodule.py
:pythondef greet(name):
return f"Hello, {name}!"
在另一个文件中导入:
pythonimport mymodule
print(mymodule.greet("Alice"))
列表推导式是一种简洁的方式来创建列表。
pythonsquares = [x**2 for x in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Lambda 表达式用于定义匿名函数。
pythonadd = lambda x, y: x + y
print(add(5, 3)) # 输出: 8
Python 提供了许多标准库,用于处理各种任务:
os
:操作系统接口。datetime
:日期和时间处理。random
:随机数生成。json
:JSON 数据处理。示例:
pythonimport random
print(random.randint(1, 10)) # 随机生成 1 到 10 的整数
装饰器用于修改函数或方法的行为。
pythondef log_function(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_function
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# 输出:
# Calling function greet
# Hello, Alice!
迭代器是一个可以记住遍历位置的对象。它从集合的第一个元素开始访问,直到所有的元素被访问完结束。
iter()
和 next()
方法:pythonmy_list = [1, 2, 3]
it = iter(my_list)
print(next(it)) # 输出: 1
print(next(it)) # 输出: 2
生成器是一种特殊的迭代器,使用函数和 yield
语句来实现。
pythondef my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value) # 输出: 1, 2, 3
pythongen = (x**2 for x in range(5))
for num in gen:
print(num) # 输出: 0, 1, 4, 9, 16
上下文管理器允许你在不需要手动管理资源的情况下执行代码块。最常用的例子是文件操作。
with
语句:pythonwith open('example.txt', 'w') as file:
file.write('Hello, World!')
# 文件会自动关闭
__enter__
和 __exit__
方法来创建自定义上下文管理器。pythonclass MyContextManager:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting the context")
with MyContextManager() as manager:
print("Inside the context")
# 输出:
# Entering the context
# Inside the context
# Exiting the context
装饰器不仅可以用来记录日志,还可以用于缓存、权限验证等场景。
pythondef repeat(num_times):
def decorator_repeat(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator_repeat
@repeat(num_times=3)
def greet(name):
print(f"Hello {name}")
greet("Alice")
# 输出:
# Hello Alice
# Hello Alice
# Hello Alice
Python 提供了多种方式来进行并发编程,包括线程、进程和异步 I/O。
threading
模块:pythonimport threading
import time
def worker():
print(f"Thread {threading.current_thread().name} starting")
time.sleep(2)
print(f"Thread {threading.current_thread().name} finishing")
threads = []
for i in range(3):
thread = threading.Thread(target=worker)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
multiprocessing
模块:pythonfrom multiprocessing import Process
import os
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
def f(name):
info('function f')
print('hello', name)
if __name__ == '__main__':
info('main line')
p = Process(target=f, args=('bob',))
p.start()
p.join()
asyncio
模块:pythonimport asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(say_after(1, 'hello'))
task2 = asyncio.create_task(say_after(2, 'world'))
await task1
await task2
asyncio.run(main())
元类是类的类,用于控制类的行为。反射则是在运行时检查或修改类结构的能力。
pythonclass Meta(type):
def __new__(cls, name, bases, dct):
print("Creating class", name)
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
obj = MyClass()
pythonclass Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(getattr(p, "name")) # 输出: Alice
setattr(p, "age", 25)
print(hasattr(p, "age")) # 输出: True
delattr(p, "age")
Python 提供了 re
模块来处理正则表达式。
pythonimport re
pattern = r'\d+'
text = "There are 123 apples and 456 oranges."
matches = re.findall(pattern, text)
print(matches) # 输出: ['123', '456']
pythonresult = re.sub(pattern, 'XXX', text)
print(result) # 输出: There are XXX apples and XXX oranges.
Python 在数据科学领域非常流行,主要得益于一些强大的第三方库,如 NumPy、Pandas、Matplotlib 和 Scikit-learn。
pythonimport numpy as np
arr = np.array([1, 2, 3])
print(arr * 2) # 输出: [2 4 6]
pythonimport pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
print(df.head()) # 输出前几行
pythonimport matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
Python 有许多优秀的 Web 框架,如 Django 和 Flask。
pythonfrom flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
app.run()