前言
承接上文,复习完字符串,根据考纲,基本数据类型中还有数字尚未复习,那么今天火速复习一下!
数字
众所周知,数字分为整型(int)、浮点型(float)、复数(complex),数字的运算除了加减乘除之外,还有取余、取整等运算。
本次复习我们跳过以上,重点复习一下有关数字的函数。
数字类型转换
int(x [,base ]) 将x转换为一个整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串
......
数字函数
abs(x) 返回x的绝对值
ceil(x) 返回x的上入整数
exp(x) 返回e的x次幂
floor(x) 返回x的下舍整数
max(x1,x2,...) 返回最大值
min(x1,x2,...) 返回最小值
pow(x,y) x的y次方,相当于x**y
......
随机数函数
有关随机数的函数,基本上要用到random库,而random库也是计算机二级必考点。
dir(random) [\'BPF\', \'LOG4\', \'NV_MAGICCONST\', \'RECIP_BPF\', \'Random\', \'SG_MAGICCONST\', \'SystemRandom\', \'TWOPI\',
\'_Sequence\', \'_Set\', \'__all__\', \'__builtins__\', \'__cached__\', \'__doc__\', \'__file__\', \'__loader__\',
\'__name__\', \'__package__\', \'__spec__\', \'_accumulate\', \'_acos\', \'_bisect\', \'_ceil\', \'_cos\', \'_e\',
\'_exp\', \'_inst\', \'_log\', \'_os\', \'_pi\', \'_random\', \'_repeat\', \'_sha512\', \'_sin\', \'_sqrt\', \'_test\',
\'_test_generator\', \'_urandom\', \'_warn\', \'betavariate\', \'choice\', \'choices\', \'expovariate\', \'gammavariate\',
\'gauss\', \'getrandbits\', \'getstate\', \'lognormvariate\', \'normalvariate\', \'paretovariate\', \'randint\', \'random\',
\'randrange\', \'sample\', \'seed\', \'setstate\', \'shuffle\', \'triangular\', \'uniform\', \'vonmisesvariate\', \'weibullvariate\']
主要讲一讲常用的choice(),choices(),randint(),random(),randrange(),shuffle(),uniform()
import random random.choice([1,2,3,4,5]) #从序列中随机抽取一个元素 random.choices([1,2,3,4,5], k=5) #从序列中随机选取k次元素,组成列表,可分配权重 random.randint(0,9) #从范围内随机选一个整数 random.random() #从0,1间随机选一个浮点数,不接受参数 random.randrange(0,100,2) #从范围内按指定数字递增的顺序随机一个数 random.shuffle(list) #将序列随机排序 random.uniform(0,9) #从范围内随机选一个浮点数
(详情参见https://www.runoob.com/python/python-numbers.html)