新手小白学会这30个函数就可以玩转python了

  1. print() – 打印输出内容到控制台
print("Hello, World!")
  1. len() – 返回序列对象的长度
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 输出:3
  1. input() – 从用户获取输入
name = input("请输入您的名字:")
print("您好," + name)
  1. str() – 将对象转换为字符串
number = 10
print("The number is: " + str(number))
  1. int() – 将对象转换为整数
age = int(input("请输入您的年龄:"))
print("您的年龄是:" + str(age))
  1. float() – 将对象转换为浮点数
pi = float("3.14")
print(pi)
  1. range() – 返回指定范围的整数序列
numbers = list(range(1, 6))
print(numbers) # 输出:[1, 2, 3, 4, 5]
  1. max() – 返回最大值
numbers = [5, 10, 3, 8]
print(max(numbers)) # 输出:10
  1. min() – 返回最小值
numbers = [5, 10, 3, 8]
print(min(numbers)) # 输出:3
  1. sum() – 返回序列对象中元素的总和
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # 输出:15
  1. abs() – 返回一个数的绝对值
print(abs(-10)) # 输出:10
  1. round() – 四舍五入取整
print(round(3.1415, 2)) # 输出:3.14
  1. sorted() – 对序列对象进行排序
numbers = [5, 2, 8, 3, 1]
print(sorted(numbers)) # 输出:[1, 2, 3, 5, 8]
  1. type() – 返回对象的类型
print(type("Hello")) # 输出:<class 'str'>
  1. str.upper() – 将字符串转换为大写
text = "hello"
print(text.upper()) # 输出:HELLO
  1. str.lower() – 将字符串转换为小写
text = "WORLD"
print(text.lower()) # 输出:world
  1. str.capitalize() – 将字符串的首字母大写
text = "hello world"
print(text.capitalize()) # 输出:Hello world
  1. str.split() – 将字符串以空格分割为列表
text = "hello world"
print(text.split()) # 输出:['hello', 'world']
  1. str.replace() – 替换字符串中的指定字符
text = "hello world"
print(text.replace("world", "Python")) # 输出:hello Python
  1. list.append() – 向列表末尾添加元素
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # 输出:['apple', 'banana', 'cherry']
  1. list.pop() – 删除列表中的最后一个元素
fruits = ["apple", "banana", "cherry"]
fruits.pop()
print(fruits) # 输出:['apple', 'banana']
  1. list.sort() – 对列表进行排序
numbers = [5, 2, 8, 3, 1]
numbers.sort()
print(numbers) # 输出:[1, 2, 3, 5, 8]
  1. list.reverse() – 反转列表元素的顺序
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) # 输出:['cherry', 'banana', 'apple']
  1. dict.get() – 返回字典中指定键的值
student = {"name": "John", "age": 18}
print(student.get("age")) # 输出:18
  1. dict.keys() – 返回字典中所有的键
student = {"name": "John", "age": 18}
print(student.keys()) # 输出:dict_keys(['name', 'age'])
  1. dict.values() – 返回字典中所有的值
student = {"name": "John", "age": 18}
print(student.values()) # 输出:dict_values(['John', 18])
  1. dict.update() – 合并两个字典
student1 = {"name": "John"}
student2 = {"age": 18}
student1.update(student2)
print(student1) # 输出:{'name': 'John', 'age': 18}
  1. set.add() – 向集合中添加元素
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # 输出:{'apple', 'banana', 'cherry'}
  1. set.remove() – 从集合中删除元素
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) # 输出:{'apple', 'cherry'}
  1. open() – 打开文件并返回文件对象
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

已发布

分类

标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注