print("Hello, World!")2. 长度计算:len() 函数获取序列(列表/字符串等)的元素个数
fruits = ["apple", "banana", "cherry"]print(len(fruits)) # 输出:3
3. 接收用户输入:input() 函数暂停程序并获取终端输入的内容
name=input("请输入您的名字:")print("您好,"+ name)
4. 类型转换:str() 把其他类型数据转为字符串类型
number = 10print("The number is:" + str(number))
5. 类型转换:int() 把符合格式的对象转为整数类型
age=int(input("请输入您的年龄:"))print("您的年龄是:"+str(age))
6. 类型转换:float() 把符合格式的对象转为浮点数类型
pi = float("3.14")print(pi)
7. 生成整数序列:range() 函数创建指定范围的整数序列(左闭右开)
numbers = list(range(1, 6))print(numbers)#输出:[1,2,3,4,5]
8. 最大值获取:max() 函数返回序列中的最大元素
numbers = [5, 10, 3, 8]print(max(numbers)) # 输出:10
9. 最小值获取:min() 函数返回序列中的最小元素
numbers = [5, 10, 3, 8]print(min(numbers)) # 输出:3
10. 求和计算:sum() 函数计算序列中所有元素的总和
numbers = [1, 2, 3, 4, 5]print(sum(numbers)) # 输出:15
11. 绝对值计算:abs() 函数返回数字的绝对值
print(abs(-10))#输出:10print(round(3.1415,2)) # 输出:3.1413. 排序操作:sorted() 函数对序列排序(返回新列表,原列表不变)
numbers = [5,2, 8,3, 1]print(sorted(numbers)) # 输出:[1,2, 3,5,8]
14. 类型判断:type() 函数返回对象的具体数据类型
print(type("Hello")) # 输出:<class 'str'>15. 字符串大写:str.upper() 方法将字符串所有字符转为大写
text = "hello"print(text.upper()) # 输出:HELL0
16. 字符串小写:str.lower() 方法将字符串所有字符转为小写
text = "WORLD"print(text.lower()) # 输出:world
17. 首字母大写:str.capitalize() 方法将字符串首字母大写,其余小写
text = "hello world"print(text.capitalize()) # 输出:Hello world
18. 字符串分割:str.split() 方法按指定分隔符拆分字符串(默认空格)
text = "hello world"print(text.split()) # 输出:['hello', 'world']
19. 字符串替换:str.replace() 方法替换字符串中指定子串
text = "hello world"print(text.replace("world","Python")) # 输出:hell(
20. 列表追加:list.append() 方法向列表末尾添加单个元素
fruits = ["apple", "banana"]fruits.append("cherry")print(fruits)# 输出:['apple',banana,'cherry']
21. 列表删除:list.pop() 方法删除列表最后一个元素(可指定索引)
fruits = ["apple", "banana", "cherry"]fruits.pop()输出:['apple',‘banana']print(fruits)#
22. 列表排序:list.sort() 方法对列表原地排序(修改原列表)
numbers = [5, 2, 8, 3, 1]numbers.sort()print(numbers) # 输出:[1,2,3,5,8]
23. 列表反转:list.reverse() 方法反转列表元素顺序(原地修改)
fruits = ["apple","banana","cherry"]fruits.reverse()print(fruits)# 输出:['cherry','apple'lbanana
24. 字典取值:dict.get() 方法获取指定键的值(键不存在时返回None,避免报错)
student = {"name": "John", "age": 18}print(student.get("age")) # 输出: 18
25. 字典取键:dict.keys() 方法返回字典中所有键的视图对象
student = {"name":"John","age": 18}print(student.keys()) # 输出:dict_keys(['name','age']
26. 字典取值:dict.values() 方法返回字典中所有值的视图对象
student = {"name":"John", "age":18}print(student.values()) # 输出:dict_values(['John', 18])
27. 字典合并:dict.update() 方法将另一个字典的键值对合并到当前字典
studentl = {"name": "John"}student2 = {"age": 18}studentl.update(student2)print(studentl) # 输出:{'name':'John','age': 18}
28. 集合添加:set.add() 方法向集合中添加唯一元素(集合无重复)
fruits = {"apple", "banana"}fruits.add("cherry")print(fruits) # 输出:{'apple','banana''cherry'}
29. 集合删除:set.remove() 方法删除集合中指定元素(元素不存在会报错)
fruits = ("apple", "banana", "cherry"}fruits.remove("banana")print(fruits) # 输出:{'apple','cherry'}
30. 文件操作:open() 函数打开文件(推荐用with语句自动关闭文件)
file = open("example.txt", "r")content = file.read()print(content)file.close()