Python中最有用的10个函数
发布时间:2023-05-23 09:37:06
1. print()
print()函数用于输出文本内容。可以在括号内放置需要输出的内容,多个值之间使用逗号分隔。
示例:
print("Hello World!")
输出:
Hello World!
2. input()
input()函数用于获取用户的输入,程序会暂停并等待,直到用户在控制台输入了一些内容并按下“回车”才会继续执行。
示例:
name = input("请输入您的名字:")
print("您好," + name + "!")
输出:
请输入您的名字:Alice 您好,Alice!
3. len()
len()函数用于获取字符串、列表、元组等数据类型的长度。例如,len(str)可以返回字符串中包含的字符数。
示例:
text = "Hello World!" print(len(text))
输出:
12
4. range()
range()函数用于生成整数序列。可以指定一个起始值、一个终止值和一个步长。
示例:
for i in range(0, 10, 2):
print(i)
输出:
0 2 4 6 8
5. str()
str()函数用于将其他数据类型转换为字符串。
示例:
num = 12345 result = str(num) print(result)
输出:
12345
6. int()
int()函数用于将其他数据类型转换为整数。
示例:
text = "100" result = int(text) print(result)
输出:
100
7. float()
float()函数用于将其他数据类型转换为浮点数。
示例:
text = "3.1415926" result = float(text) print(result)
输出:
3.1415926
8. type()
type()函数用于获取数据类型。
示例:
num = 10 print(type(num)) text = "Hello World!" print(type(text))
输出:
<class 'int'> <class 'str'>
9. sum()
sum()函数用于求和。可以对列表、元组等类型的数据进行求和。
示例:
numbers = [1, 2, 3, 4, 5] result = sum(numbers) print(result)
输出:
15
10. sorted()
sorted()函数用于对列表进行排序。可以指定升序或降序排列,也可以通过自定义函数指定排序规则。
示例:
numbers = [5, 2, 4, 1, 3] result = sorted(numbers) print(result)
输出:
[1, 2, 3, 4, 5]
