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

Python内置函数:常用的内置函数及其用法

发布时间:2023-12-04 00:27:39

Python内置函数是指在Python解释器中不需要导入任何模块就可以直接使用的函数。Python内置函数有很多,下面是一些常用的内置函数及其用法。

1. print(): 打印输出功能,可以将字符串、变量或表达式的值输出到终端。

   例如:print("Hello, World!")

2. type(): 获取变量的数据类型。

   例如:type(10)   # int

        type(3.14)   # float

        type("hello")   # str

3. len(): 获取字符串、列表、元组等对象的长度。

   例如:len("hello")   # 5

        len([1, 2, 3, 4, 5])   # 5

4. input(): 从终端读取用户的输入。

   例如:name = input("Please enter your name: ")

5. int(): 将一个数值或字符串转换为整型。

   例如:int("10")   # 10

6. float(): 将一个数值或字符串转换为浮点型。

   例如:float("3.14")   # 3.14

7. str(): 将对象转换为字符串。

   例如:str(10)   # "10"

8. list(): 将一个可迭代对象转换为列表。

   例如:list("hello")   # ['h', 'e', 'l', 'l', 'o']

9. tuple(): 将一个可迭代对象转换为元组。

   例如:tuple([1, 2, 3])   # (1, 2, 3)

10. range(): 生成一个整数序列。

    例如:range(1, 10)   # [1, 2, 3, 4, 5, 6, 7, 8, 9]

11. max(): 返回可迭代对象中的最大值。

    例如:max([1, 3, 5])   # 5

12. min(): 返回可迭代对象中的最小值。

    例如:min([-1, 3, 5])   # -1

13. sum(): 返回可迭代对象中所有元素的和。

    例如:sum([1, 2, 3, 4, 5])   # 15

14. abs(): 返回一个数的绝对值。

    例如:abs(-10)   # 10

15. round(): 对一个数进行四舍五入。

    例如:round(3.14)   # 3

         round(3.56)   # 4

16. sorted(): 对可迭代对象进行排序。

    例如:sorted([3, 1, 4, 2, 5])   # [1, 2, 3, 4, 5]

17. pow(): 计算一个数的幂。

    例如:pow(2, 3)   # 8

18. divmod(): 返回两个数相除的商和余数。

    例如:divmod(10, 3)   # (3, 1)

19. isinstance(): 判断一个对象是否是指定类型。

    例如:isinstance(10, int)   # True

20. help(): 获取对象的帮助信息。

    例如:help(print)

这些是Python内置函数中的常用函数及其用法,通过使用这些函数,可以方便地完成各种常见的操作。在编写Python程序时,经常会用到这些函数,掌握它们的用法是非常重要的。