以下是一个简单的Python脚本示例,它包含了一些基本的Python概念,比如变量、数据类型、控制流、函数、列表、字典、集合和异常处理等。
# Python基础知识示例
# 变量和数据类型
number = 42 # 整数
float_number = 3.14 # 浮点数
string = "Hello, Python!" # 字符串
# 列表
list_example = [1, 2, 3, 'a', 'b', 'c']
list_example.append('new item') # 添加元素
# 元组(不可变序列)
tuple_example = (1, 2, 3)
# 字典
dict_example = {
'name': 'Alice',
'age': 30,
'is_student': False
}
# 集合
set_example = {1, 2, 3, 4, 5}
set_example.add(6) # 添加元素
# 控制流:if语句
if number > 0:
print("The number is positive.")
# 控制流:for循环
for item in list_example:
print(item)
# 函数定义和调用
def greet(name):
print(f"Hello, {name}!")
greet("World")
# 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
# 类和对象
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return "Woof!"
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) # Buddy
print(my_dog.bark()) # Woof!
# 模块和包
import math
print(math.sqrt(16)) # 4.0
# 装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# 匿名函数(Lambda函数)
add = lambda x, y: x + y
print(add(5, 3)) # 8
# 推导式
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 文件操作
with open('example.txt', 'w') as file:
file.write("Hello, file!")
with open('example.txt', 'r') as file:
content = file.read()
print(content) # Hello, file!
# 这就是一个包含多种Python基础知识的简单示例。