这些代码片段涵盖了Python编程的一些常用方面,包括日期和时间操作、列表排序、字符串格式化、文件读写以及包和模块的使用。继续探索和学习这些概念,以及其他相关的Python特性,将使你的编程能力不断提升。
1.输出语句:
print("Hello, World!") # 打印字符串
2.变量和赋值:
x = 5 # 整数
y = 3.14 # 浮点数
name = "Alice" # 字符串
is_true = True # 布尔值
3.输入语句:
name = input("请输入你的名字:")
print("你好," + name)
4.条件语句:
x = 10
if x > 5:
print("x大于5")
elif x == 5:
print("x等于5")
else:
print("x小于5")
5.循环语句:
for循环:
python
for i in range(5):
print(i)
while循环:
python
i = 0
while i < 5:
print(i)
i += 1
6.列表:
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # 输出第一个元素
fruits.append("grape") # 添加元素
fruits.remove("banana") # 移除元素
7.字典:
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person["name"]) # 输出键为"name"的值
person["age"] = 26 # 修改键为"age"的值
del person["city"] # 删除键为"city"的键值对
8.函数:
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # 调用函数并传递参数
9.数字运算:
x = 5
y = 3
print(x + y) # 加法
print(x - y) # 减法
print(x * y) # 乘法
print(x / y) # 除法
print(x % y) # 取模运算
print(x ** y) # 幂运算
10.字符串操作:
text = "Hello, World!"
print(len(text)) # 字符串长度
print(text.upper()) # 转换为大写
print(text.lower()) # 转换为小写
print(text.replace("Hello", "Hi")) # 替换字符串
print(text.split(",")) # 拆分字符串为列表
11.文件操作:
# 写入文件
file = open("myfile.txt", "w")
file.write("Hello, World!")
file.close()
# 读取文件
file = open("myfile.txt", "r")
content = file.read()
print(content)
file.close()
12.异常处理:
try:
x = 5 / 0
except ZeroDivisionError:
print("除数不能为零")
13.导入模块:
import math
print(math.sqrt(16)) # 平方根
print(math.pi) # 圆周率
14.列表推导式:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print(squared_numbers)
15.面向对象编程:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
person = Person("Alice", 25)
person.greet()
16.日期和时间操作:
import datetime
current_time = datetime.datetime.now()
print(current_time)
print(current_time.year)
print(current_time.month)
print(current_time.day)
17.列表排序:
numbers = [3, 1, 4, 2, 5]
numbers.sort() # 升序排序
print(numbers)
numbers.sort(reverse=True) # 降序排序
print(numbers)
18.字符串格式化:
name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))
# 使用f-string(Python 3.6+)
print(f"My name is {name} and I'm {age} years old.")
19.文件读写:
# 写入文件
with open("myfile.txt", "w") as file:
file.write("Hello, World!")
# 读取文件
with open("myfile.txt", "r") as file:
content = file.read()
print(content)
20.包和模块:
创建模块(例如,my_module.py):
def greet(name):
print("Hello, " + name + "!")
在另一个脚本中使用模块:
python
import my_module
my_module.greet("Alice")