欢迎访问宙启技术站
智能推送

Python内置函数的介绍与示例

发布时间:2023-06-10 22:30:18

Python作为一种高级编程语言,提供了丰富的内置函数,这些函数能够帮助我们非常便捷地完成各种操作。以下是Python内置函数的介绍与示例:

1. print()

print()函数用来输出指定的字符串、数字等内容。可以用逗号分隔多个参数,将它们打印为一个字符串。示例:

print("Hello, world!")

print(2+3, " is equal to ", 5)

输出结果:

Hello, world!

5 is equal to 5

2. input()

input()函数用来获取用户的输入。输入的内容会被当做字符串返回。示例:

name = input("What's your name? ")

print("Nice to meet you, " + name + "!")

输出结果:

What's your name? John

Nice to meet you, John!

3. len()

len()函数用来获取字符串、元组、列表等的长度。示例:

a = "Hello, world!"

print(len(a))

输出结果:

13

4. type()

type()函数用来获取变量的类型。示例:

a = 10

b = "Hello"

c = [1, 2, 3]

print(type(a))

print(type(b))

print(type(c))

输出结果:

<class 'int'>

<class 'str'>

<class 'list'>

5. str()

str()函数用来将指定的对象转换成字符串。示例:

a = 10

b = str(a)

print(b)

print(type(b))

输出结果:

10

<class 'str'>

6. int()

int()函数用来将指定的对象转换成整数。示例:

a = "10"

b = int(a)

print(b)

print(type(b))

输出结果:

10

<class 'int'>

7. float()

float()函数用来将指定的对象转换成浮点数。示例:

a = "3.14"

b = float(a)

print(b)

print(type(b))

输出结果:

3.14

<class 'float'>

8. max()

max()函数用来获取指定序列中的最大值。示例:

a = [1, 2, 3, 4, 5]

print(max(a))

输出结果:

5

9. min()

min()函数用来获取指定序列中的最小值。示例:

a = [1, 2, 3, 4, 5]

print(min(a))

输出结果:

1

10. abs()

abs()函数用来获取指定数值的绝对值。示例:

a = -10

print(abs(a))

输出结果:

10

11. round()

round()函数用来对指定的数值进行四舍五入取整。示例:

a = 3.1415926

print(round(a, 2))

输出结果:

3.14

12. sum()

sum()函数用来对指定序列进行求和。示例:

a = [1, 2, 3, 4, 5]

print(sum(a))

输出结果:

15

13. range()

range()函数用来生成一个整数序列。可以指定起始值、终止值和步长。示例:

a = range(1, 10, 2)

for i in a:

    print(i)

输出结果:

1

3

5

7

9

14. zip()

zip()函数将多个序列打包成一个元组。可以用于并行迭代。示例:

a = [1, 2, 3]

b = ['a', 'b', 'c']

c = zip(a, b)

for i in c:

    print(i)

输出结果:

(1, 'a')

(2, 'b')

(3, 'c')

15. map()

map()函数将指定的函数应用到序列的每个元素上,并返回一个新的列表。示例:

a = [1, 2, 3]

def square(x):

    return x**2

b = map(square, a)

print(list(b))

输出结果:

[1, 4, 9]

以上就是Python内置函数的介绍与示例,这些函数大大简化了编程过程,也提高了代码的可读性和可维护性,是Python编程的必备工具。