Python编程-从入门到实践 Eric Matthes 著 袁国忠 译 - - 第二章 动手试一试
1 # 2.2 动手试一试 2 # 2_1 简单消息: 将一条消息存储到变量中,再将其打印出来。 3 message = 'python 编程从入门到实践——第一个程序开始了。' 4 print (message) 5 6 # 2_2 多条简单消息: 将一条消息存储到变量中,将其打印出来;再将变量的值修改为一条新消息,并将其打印出来。 7 news = 'hello world!' 8 print (news) 9 news = 'hello python!' 10 print (news) 11 12 # 2.3 动手试一试 13 # 2_3 个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息。显示的消息应非常简单。 14 name = 'Yuan Dong' 15 print ('Hello ' + name + ', would you like to learn some Python today?') 16 17 # 2_4 调整名字的大小写: 将一个人名存储到一个变量中,再以小写、大写和首字母大写的方式显示这个人名。 18 name = 'yuan dong' 19 print (name.lower()) # 全部小写 20 print (name.upper()) # 全部大写 21 print (name.title()) # 仅首字母大写 22 23 # 2_5 名言: 找一句你钦佩的名人说的名言,将这个名人的姓名和他的名言打印出来。 24 famous_person = 'Albert Einstein' 25 message = 'A person who never made a mistake never teied anything new.' 26 print (famous_person + ' once said, '+ '"' + message + '"') 27 28 # 2_6 名言2: 重复练习2-5,但将名人的姓名存储在变量famous_person 中,再创建要显示的消息,并将其存储在变量message 中,然后打印这条消息。 29 # 同上 30 31 # 2_7 剔除人名中的空白: 存储一个人名,并在其开头和末尾都包含一些空白字符。务必至少使用字符组合"\t" 和"\n" 各一次。 32 # 打印这个人名,以显示其开头和末尾的空白。然后,分别使用剔除函数lstrip() 、rstrip() 和strip() 对人名进行处理,并将结果打印出来。 33 name = ' \t yuan dong \n' 34 print (name) 35 print (name.lstrip()) # 剔除开头空白 36 print (name.rstrip()) # 剔除末尾空白 37 print (name.strip()) # 剔除两端空白 38 39 # 2.4 40 # 2_8 数字8: 编写4个表达式,它们分别使用加法、减法、乘法和除法运算,但结果都是数字8。为使用print 语句来显示结果,务必将这些表达式用括号括起来, 41 # 也就是说,你应该编写4行类似于下面的代码: 42 # print(5+3) 43 # 输出应为4行,其中每行都只包含数字8。 44 print (5 + 3) 45 print (10 - 2) 46 print (2 * 4) 47 print (16 // 2) 48 49 # 2_9 最喜欢的数字: 将你最喜欢的数字存储在一个变量中,再使用这个变量创建一条消息,指出你最喜欢的数字,然后将这条消息打印出来。 50 number = '0316' 51 message = '我最喜欢的数字是:'+ number 52 print(message) 53 54 # 2_10 添加注释 55 # 以上已经完成 56 57 # 2_11 Python之禅: 在Python终端会话中执行命令import this ,并粗略地浏览一下其他的指导原则。 58 import this # 查看Python 之禅 59 ''' 60 The Zen of Python, by Tim Peters 61 62 Beautiful is better than ugly. 63 Explicit is better than implicit. 64 Simple is better than complex. 65 Complex is better than complicated. 66 Flat is better than nested. 67 Sparse is better than dense. 68 Readability counts. 69 Special cases aren't special enough to break the rules. 70 Although practicality beats purity. 71 Errors should never pass silently. 72 Unless explicitly silenced. 73 In the face of ambiguity, refuse the temptation to guess. 74 There should be one-- and preferably only one --obvious way to do it. 75 Although that way may not be obvious at first unless you're Dutch. 76 Now is better than never. 77 Although never is often better than *right* now. 78 If the implementation is hard to explain, it's a bad idea. 79 If the implementation is easy to explain, it may be a good idea. 80 Namespaces are one honking great idea -- let's do more of those! 81 '''