一、python极简输出
如上图所示,上面只有一个错误答案,我们用排除法知道,错误的是答案B,但这里面有个有趣的答案C,就是[print(languages[i], ':', years[i]) for i in range(0, len(languages))],即我们将print和for 循环一起使用,一句话就解决了问题,值得学习。这是对应的运行效果:
二、 break和continue
if __name__ == '__main__': install = { "Windows": "请下载 Windows 安装包安装:https://www.python.org/downloads/windows/", "CentOS": "使用yum包管理器,执行命令:yum install -y python3", "Ubuntu": "使用apt-get包管理器,执行命令:apt-get install -y python3", "MacOS": "安装brew包管理器,然后执行命令: brew install python3", } shortcut_keys = {} for platform in install: key = platform[0].lower() shortcut_keys[key] = platform # while True: # ret = input("请选择安装平台[w/c/u/m, 按q退出]:") # if ret == 'q': # break # platform = shortcut_keys.get(ret) # if platform is None: # print("不支持的平台") # else: # doc = install.get(platform) # print(f"{platform}: {doc}") # while True: # ret = input("请选择安装平台[w/c/u/m, 按q退出]:") # platform = shortcut_keys.get(ret) # # if ret == 'q': # break # # if platform is None: # print("不支持的平台") # continue # # doc = install.get(platform) # print(f"{platform}: {doc}") # # while True: # ret = input("请选择安装平台[w/c/u/m, 按q退出]:") # if ret != 'q': # platform = shortcut_keys.get(ret) # if platform is not None: # doc = install.get(platform) # print(f"{platform}: {doc}") # else: # print("不支持的平台") # else: # break #答案A while True: ret = input("请选择安装平台[w/c/u/m, 按q退出]:") platform = shortcut_keys.get(ret) if ret == 'q': break if platform is None: print("不支持的平台") continue doc = install.get(platform) print(f"{platform}: {doc}") #答案B while True: ret = input("请选择安装平台[w/c/u/m, 按q退出]:") platform = shortcut_keys.get(ret) if ret == 'q': break if platform is None: print("不支持的平台") break doc = install.get(platform) print(f"{platform}: {doc}")
如图所示,题干和答案都比较长,我们在日常中也容易忽略这个简单的错误,在一个本该继续执行的地方加了个break导致程序异常终止了。