python-异常/文件/时间/随机数
def exception_test(): try: x = float(input("请输入被除数:")) y = float(input("请输入除数:")) z = x/y print(z) except ZeroDivisionError: print("除数不能为零!") # except ValueError: # print("数值类型错误") else: print("没有捕获到对应的异常") finally: print("计算结束。。。") def os_file_test(): import os print(os.listdir()) # 目录列表 print(os.getcwd()) # 当前目录 print(os.path.exists("D:Demo")) # 判断目录 f = open("./test.txt") # res1 = f.read() # print(res1) # res2 = f.readline() # print(res2) res3 = f.readlines() print(res3) def time_test(): import time for i in range(10): print(i) time.sleep(0.01) cur_time = time.time() print(cur_time) # 转为时间戳 print(time.mktime(time.localtime())) # 转为特定格式 print(time.asctime(time.localtime())) print(time.ctime(int(cur_time))) # 转换成时间字符串 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print(time.strftime("%Y-%m-%d %X", time.localtime())) # 转换成时间字符穿 str_time = time.strftime("%Y-%m-%d %X", time.localtime()) print(time.strptime(str_time, "%Y-%m-%d %H:%M:%S")) def random_test(): import random # 0-1随机数 print(random.random()) # 一定范围的随机数 print(random.uniform(2, 3)) # 一定范围的整数 print(random.randint(2, 4)) # 包括2,4 # 序列中获取一个随机数 print(random.randrange(10, 100, 2)) # 10,12,14...,96,98 # random.choice() 是从序列中获取一个随机元素,可以是字符串,元组,列表等 print(random.choice("python test")) print(random.choice(["1", "2", "3", "4"])) print(random.choice(("1", "2", "3", "4"))) # random.shuffle() 是将一个列表中的元素打乱 lists = [1, 2, 3, 4, 5, 6, 7, 8, 9] random.shuffle(lists) print(lists) # random.sample()是从指定序列中随机获取指定长度的片断 listss = [i ** 3 for i in range(10)] print(listss) print(random.sample(listss, 3)) print(listss) # 原有list不变