2-2 多条简单消息: 将一条消息存储到变量中,将其打印出来;再将变量的值修改为一条新消息,并将其打印出来。

代码如下:

str = "Hello World."
print(str)
str = "ByeBye World."
print(str)

结果为

Hello World.
ByeBye World.

2-4 调整名字的大小写: 将一个人名存储到一个变量中,再以小写、大写和首字母大写的方式显示这个人名。

代码如下:

str = "python"
print(str.lower())
print(str.upper())
print(str.title())

结果为

python
PYTHON
Python

2-7 剔除人名中的空白: 存储一个人名,并在其开头和末尾都包含一些空白字符。务必至少使用字符组合”\t” 和”\n” 各一次。打印这个人名,以显示其开头和末尾的空白。然后,分别使用剔除函数lstrip() 、rstrip() 和strip() 对人名进行处理,并将结果打印出来。

代码如下:

name = ("   Donald Trump \n")
print(name) 
print(name.lstrip()) 
print(name.rstrip()) 
print(name.strip())

结果为

Donald Trump

Donald Trump

        Donald Trump
Donald Trump

2-10 添加注释: 选择你编写的两个程序,在每个程序中都至少添加一条注释。如果程序太简单,实在没有什么需要说明的,就在程序文件开头加上你的姓名和当前日期,再用一句话阐述程序的功能。

代码1如下:

name = ("   Donald Trump \n")
print(name) # print the name
print(name.lstrip()) # print without the spaces in the left
print(name.rstrip()) 
print(name.strip())

代码2如下:

str = "python"
print(str.lower())
print(str.upper())
print(str.title())

'''
comments:
the program will print 
the str in three formats.
'''

2-11 Python之禅: 在Python终端会话中执行命令import this ,并粗略地浏览一下其他的指导原则。

C:\Users\hasee>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!