python 示例代码
以下是35个python代码示例,涵盖了从基础到高级的各种应用场景。这些示例旨在帮助你学习和理解python编程的各个方面。
1. Hello, World!
# python
print("Hello, World!") #result:Hello, World!
print("Hello", "World!") #result:Hello World!
print(", ".join(["Hello", "World"])) # 输出:Hello, World
# print() 在输出时自动将逗号分隔的参数用空格连接起来。
2. 变量与数据类型
# python
x = 5 # 整数
y = 3.14 # 浮点数
name = "Alice" # 字符串
is_active = True # 布尔值
""""
py变量类型是其值的类型
a = 3 #int
a = "hello" #str
可以根据需要进行转换
a = '2'
a = int(a)
""""
3. 基本算术运算
# python
a = 10
b = 3
print(a + b) # 加法
print(a - b) # 减法
print(a * b) # 乘法
print(a / b) # 除法
print(a % b) # 取余
print(a **b) # 幂运算
4. 字符串操作
# python
s = "Hello, python!"
print(s.upper()) # 转换为大写
print(s.lower()) # 转换为小写
print(s.replace("python", "World")) # 替换字符串
print(s.split(",")) # 分割字符串
5. 列表操作
# python
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # 添加元素
fruits.remove("banana") # 移除元素
print(fruits[1]) # 访问元素
print(len(fruits)) # 列表长度
6. 元组操作
# python
coordinates = (10.0, 20.0, 30.0)
print(coordinates[0]) # 访问元素
# coordinates(0) = 15.0 # 元组不可变,会报错
7. 字典操作
# python
student = {
"name": "Bob",
"age": 20,
"courses": ["Math", "CompSci"]
}
print(student["name"]) # 访问值
student["age"] = 21 # 修改值
student["phone"] = "1234567890" # 添加键值对
for k in student.keys():
print(k,':', student[k],end = '\n') #输出字典所有元素
"""
name : Bob
age : 21
courses : ['Math', 'CompSci']
phone : 1234567890
"""
8. 集合操作
# python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # 并集
print(set1.intersection(set2)) # 交集
print(set1.difference(set2)) # 差集
9. 条件语句
# python
age = 18
if age >= 18:
print("成年人")
elif age > 13:
print("青少年")
else:
print("儿童")
10. 循环语句 - for循环
# python
for i in range(5):
print(i)
11. 循环语句 - while循环
# python
count = 0
while count < 5:
print(count)
count += 1
12. 函数定义
# python
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
13. 函数参数 - 默认值
# python
def greet(name, message="Hello"):
return f"{message}, {name}!"
print(greet("Bob"))
print(greet("Bob", "Hi"))
14. 函数参数 - 可变参数
# python
def add(*args):
return sum(args)
print(add(1, 2, 3, 4))
15. 匿名函数 - lambda
# python
add = lambda x, y: x + y
print(add(5, 3))
16. 列表推导式
# python
numbers = [1, 2, 3, 4, 5]
squares = [x **2 for x in numbers]
print(squares)
17. 字典推导式
# python
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = {k: v for k, v in zip(keys, values)}
print(dictionary)
18. 集合推导式
# python
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_even = {x for x in numbers if x % 2 == 0} # unique意为惟一的
print(unique_even)
19. 异常处理 - try-except
# python
try:
result = 10 / 0
except ZeroDivisionError:
print("除以零错误")
20. 异常处理 - try-except-else-finally
# python
try:
result = 10 / 2
except ZeroDivisionError:
print("除以零错误")
else:
print("结果是:", result)
finally:
print("执行完毕")
21. 文件操作 - 读取文件
# python
with open("example.txt", "r") as file:
content = file.read()
print(content)
22. 文件操作 - 写入文件
# python
with open("example.txt", "w") as file:
file.write("Hello, World!")
# 注意example.txt必须置于当前文件夹(程序所在文件夹)否则要求路径
23. 文件操作 - 追加文件
# python
with open("example.txt", "a") as file:
file.write("\n追加的内容")
24. 类与对象
# python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy", 3)
my_dog.bark()
25. 继承
# python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
class Cat(Animal):
def speak(self):
print(f"{self.name} says Meow!")
my_cat = Cat("Whiskers")
my_cat.speak()
26. 多态
# python
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
def make_animal_speak(animal):
animal.speak()
dog = Dog()
cat = Cat()
make_animal_speak(dog)
make_animal_speak(cat)
27. 装饰器 - 基本示例
# python
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
28. 装饰器 - 带参数
# python
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
29. 生成器 - 基本示例
# python
def countdown(n):
while n > 0:
yield n
n -= 1
for number in countdown(5):
print(number)
# python
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
print("\n\n数值小于100的项:")
for num in fibonacci():
if num >= 100:
break
print(num, end=" ")
30. 生成器表达式
# python
numbers = (x for x in range(10))
for num in numbers:
print(num)
31. 模块导入 - 导入整个模块
# python
import math
print(math.sqrt(16))
32. 模块导入 - 导入特定函数
# python
from math import sqrt
print(sqrt(25))
33. 模块导入 - 重命名模块
# python
import math as m
print(m.pi)
34. 模块导入 - 重命名函数
# python
from math import sqrt as square_root
print(square_root(36))