python中常用的内置函数和内置模块

一、InnerFuction 内置函数
1、type() 返回对象或者变量的数据类型

     print(type("嘻嘻"))            #class_str

      a=3

     print(type(a))                  #class_int

2、abs() 返回数字的绝对值

     print(abs(-10))     #10

3、max() 返回一组数据当中最大的值

     print(max(1,3,2))    #3

4、min() 返回一组数据当中的最小值

      print(min(1,3,2))    #1

5、id() 返回数据在内存中的地址

     print(id(1))   

     print(id(2))

     print(id(3))

     print(id(4))

        预显示数据如果第一次出现则创建对象,如果二次出现则复用第一次创建的那个对象即可,但在python里,会自动为一些常见的常量预先定义在堆内存中。

注意:

     print(id(5))  #从上到下第一次出现的数据常量

     print(id(5))  #已存在的常量5,直接复用

6、int()  将字符串转数字

7、float()  将字符串或整型转小数

8、str()  将其他转为字符串

9、bool()  true or false

10、len() 查看数据长度

    序列:一组数据 (列表,元祖,字典,集合,字符串)

      print(len("abcd"))   #4

      print(len("嘻嘻"))  #2

11、bin() 转二进制

       print(bin(149))    #0b10010101

12、oct() 转八进制

       print(oct(149))     #0o225

13、hex() 转十六进制

        print(hex(149))    #0x95

14、ord() 返回传入的字符所对应的ASCII值

        print(ord('a'))  #97。每次传入只能有一个字符

15、chr() 返回传入数字对应的ASCII字符

        print(chr(97))   #a

 
             实例:

                   1、如何判断输入的一个字符是大写字母还是小写字母还是数字呢?

                          #97:a     65:A       48:0

                          c=input("输入一个字符:")

                          #ord('a') <= ord(c) <= ord('z')      判断是否为小写字母

                          #ord(''A) <= ord(C) <= ord('Z')     判断是否为大写字母

                          #ord('0') <= ord(c) <= ord('9')      判断是否为数字

 

                       2、如何将小写字母转为大写字母?

                             chr(ord(c)-32)

 

16、round()   四舍五入

       print(round(5.666))   #6

       print(round(5.444))   #5

 

二、内置模块
1、random模块

        import random     #导入模块(若要使用相关内容必须写)

(1)random.randint(a,b) 随机产生一个[a,b]之间的数字

        print(random.randint(1,10))  #随机产生1~10的数字,包括1和10

(2)random.random() 随机产生一个[0,1)之间的小数

        print(random.random())  #随机产生一个0~1之间的小数,包括0不包括1

(3)random.randrange()从给定的范围中选择一个随机整数

       print(random.randrange(10))       #[0,10)

       print(random.randrange(5,10))      #[5,10)

 

2、math模块

      import math      #导入模块(若要使用相关内容必须写)

(1)math.pi() 圆周率

      print(math.pi)       #3.141592653589793

(2)math.e()  自然常数e

      print(math.e)        #2.718281828459045

(3)math.pow() 一个数的n次方

        print(math.pow(2,8))        #2**8

(4)math.fabs() 取相反数

        print(math.fabs(-3.14))     #3.14

(5)math.ceil() 获取大于该数字的最小整数

         print(math.ceil(3.13))        #4

         print(math.ceil(-2.89))       #-2

(6)math.floor() 获取小于该数字的最大整数

         print(math.floor(3.96))       #3

         print(math.floor(-3.96))      #-4

(7)math.sqrt()  #开平方

          print(math.sqrt(9))            #3.0


原文链接:https://blog.csdn.net/trichloromethane/article/details/106835550

posted @ 2020-06-19 16:59  逍-遥  阅读(694)  评论(0编辑  收藏  举报
民营企业网B2B