1. 基础语法和数据类型:
# 变量和数据类型
name = "John"
age = 25
height = 1.75
is_student = False
# 基本运算符
result = 10 + 5
is_equal = (result == 15)
# 输入和输出
user_input = input("Enter something: ")
print("You entered:", user_input)
# 条件语句和循环
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
for i in range(5):
print(i)
while age < 30:
print("Still young!")
age += 1
2. 数据结构:
# 列表
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # 输出: apple
# 字典
person = {"name": "John", "age": 25}
print(person["name"]) # 输出: John
3. 函数和异常处理:
# 函数
def greet(name):
return "Hello, " + name + "!"
result = greet("Alice")
print(result)
# 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
4. 文件操作:
# 写文件
with open("example.txt", "w") as file:
file.write("Hello, File!")
# 读文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
5. 高级主题:
# 迭代器和生成器
def square_generator(n):
for i in range(n):
yield i**2
# 装饰器
def my_decorator(func):
def wrapper():
print("Before function is called.")
func()
print("After function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
# 正则表达式
import re
pattern = re.compile(r'\b(\w+)\b')
matches = pattern.findall("This is a sample sentence.")
print(matches)
这只是一个简单的备忘单,你可以根据需要扩展它。在编写代码时,不断参考和练习这些概念,你会越来越熟悉 Python 的语法和用法。
转载请注明出处:http://www.zyzy.cn/article/detail/264/Python3