Python中常见的内置函数及其使用方式
发布时间:2023-06-05 02:20:23
Python是一种高级编程语言,提供了大量的内置函数,可以进行各种操作,如组合、排序、过滤、逻辑、字符串处理等,基本涵盖了各种基本的编程需求。下面是一些常见的Python内置函数及其使用方式。
1. print()
print()函数是Python最常用的函数,它用于在控制台中输出文本或变量。可以传递一个或多个参数,并用逗号隔开:
print("Hello World!") # 输出 Hello World!
name = "Tom"
print("My name is", name) # 输出 My name is Tom
2. len()
len()函数用于获取字符串、列表或元组的长度,例如:
str1 = "Python Programming"
list1 = [1, 2, 3, 4, 5]
tuple1 = ('a', 'b', 'c', 'd', 'e')
print(len(str1)) # 输出 19
print(len(list1)) # 输出 5
print(len(tuple1)) # 输出 5
3. range()
range()函数用于生成一个整数序列,通常用于循环中:
for i in range(5):
print(i)
# 输出:
# 0
# 1
# 2
# 3
# 4
也可以指定开始值、结束值和步长:
for i in range(2, 11, 2):
print(i)
# 输出:
# 2
# 4
# 6
# 8
# 10
4. input()
input()函数用于从控制台读取用户的输入,如:
name = input("请输入您的姓名:")
print("您好,", name)
5. type()
type()函数用于获取变量的类型,如:
x = 5 y = "Hello" z = [1, 2, 3] print(type(x)) # 输出 <class 'int'> print(type(y)) # 输出 <class 'str'> print(type(z)) # 输出 <class 'list'>
6. str()
str()函数用于将变量转换为字符串类型,如:
x = 5 y = 'world' print(str(x) + "hello") # 输出 5hello print(y + str(x)) # 输出 world5
7. int()
int()函数用于将字符串或浮点数转换为整数类型,如:
x = int('5')
y = int(3.7)
print(x) # 输出 5
print(y) # 输出 3
8. float()
float()函数用于将字符串或整数转换为浮点数类型,如:
x = float('3.14')
y = float(5)
print(x) # 输出 3.14
print(y) # 输出 5.0
9. list()
list()函数用于将元组或字符串转换为列表类型,如:
x = list(('apple', 'banana', 'cherry'))
y = list('hello')
print(x) # 输出 ['apple', 'banana', 'cherry']
print(y) # 输出 ['h', 'e', 'l', 'l', 'o']
10. tuple()
tuple()函数用于将列表或字符串转换为元组类型,如:
x = tuple(['apple', 'banana', 'cherry'])
y = tuple('hello')
print(x) # 输出 ('apple', 'banana', 'cherry')
print(y) # 输出 ('h', 'e', 'l', 'l', 'o')
11. sorted()
sorted()函数用于对列表或元组进行排序:
x = [3, 1, 7, 2, 5]
y = ('c', 'b', 'a', 'd')
print(sorted(x)) # 输出 [1, 2, 3, 5, 7]
print(sorted(y)) # 输出 ['a', 'b', 'c', 'd']
12. max()
max()函数用于获取列表或元组中的最大值:
x = [3, 1, 7, 2, 5]
y = ('c', 'b', 'a', 'd')
print(max(x)) # 输出 7
print(max(y)) # 输出 d
13. min()
min()函数用于获取列表或元组中的最小值:
x = [3, 1, 7, 2, 5]
y = ('c', 'b', 'a', 'd')
print(min(x)) # 输出 1
print(min(y)) # 输出 a
14. abs()
abs()函数用于获取数值的绝对值:
x = -5 y = 3.14 print(abs(x)) # 输出 5 print(abs(y)) # 输出 3.14
15. pow()
pow()函数用于计算指数,如:
x = pow(2, 3) print(x) # 输出 8
16. round()
round()函数用于四舍五入:
x = 3.14159 print(round(x, 2)) # 输出 3.14
