python练习-8.12
注:本代码是《python核心编程(第二版)》的第八章8-12的练习题的代码实现。
完成的功能:用户给出起始和结束的数字后给出一个下面的表格,分别显示出两个数字间所有整型的十进制、二进制、八进制及十六进制。如果字符是可打印的ASCLL符,也要打印出来。如果没有一个是可打印的字符,则省略掉ASCLL那一栏的表头。
代码实现如下:
1 def format_print(start_index, end_index): 2 seq = range(start_index, end_index + 1) 3 title = "DEC\tBIN\t\tOCT\tHEX" 4 if (end_index >=32 and end_index <=126): 5 title = "DEC\tBIN\t\tOCT\tHEX\tASCLL" 6 print title 7 print "--------------------------------------------" 8 for item in seq: 9 if item >= 32 and item <= 126: 10 print "%d\t%07d\t\t%o\t%x\t%s" % (item, int(bin(item)[2:]), item, item, chr(item)) 11 else: 12 print "%d\t%07d\t\t%o\t%x" % (item, int(bin(item)[2:]), item, item) 13 print '--------------------------------------------' 14 15 16 def showmenu(): 17 prompt1 = 'enter start index, (Q)uit:' 18 prompt2 = 'enter end index, (Q)uit:' 19 while True: 20 start_index = raw_input(prompt1).strip().lower() 21 if start_index == 'q': 22 break 23 if not start_index.isdigit(): 24 print "Error! wrong format!" 25 continue 26 else: 27 start_index = int(start_index) 28 29 end_index = raw_input(prompt2).strip().lower() 30 if end_index == 'q': 31 break 32 if not end_index.isdigit(): 33 print "Error! wrong format!" 34 continue 35 else: 36 end_index = int(end_index) 37 38 if (start_index >= end_index): 39 continue 40 format_print(start_index, end_index) 41 42 43 if __name__ == '__main__': 44 showmenu()
测试结果如下:
1 enter start index, (Q)uit:9 2 enter end index, (Q)uit:18 3 DEC BIN OCT HEX 4 -------------------------------------------- 5 9 0001001 11 9 6 10 0001010 12 a 7 11 0001011 13 b 8 12 0001100 14 c 9 13 0001101 15 d 10 14 0001110 16 e 11 15 0001111 17 f 12 16 0010000 20 10 13 17 0010001 21 11 14 18 0010010 22 12 15 -------------------------------------------- 16 enter start index, (Q)uit:26 17 enter end index, (Q)uit:41 18 DEC BIN OCT HEX ASCLL 19 -------------------------------------------- 20 26 0011010 32 1a 21 27 0011011 33 1b 22 28 0011100 34 1c 23 29 0011101 35 1d 24 30 0011110 36 1e 25 31 0011111 37 1f 26 32 0100000 40 20 27 33 0100001 41 21 ! 28 34 0100010 42 22 " 29 35 0100011 43 23 # 30 36 0100100 44 24 $ 31 37 0100101 45 25 % 32 38 0100110 46 26 & 33 39 0100111 47 27 ' 34 40 0101000 50 28 ( 35 41 0101001 51 29 ) 36 -------------------------------------------- 37 enter start index, (Q)uit:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端