python编程从入门到实践,第十章练习题编程从入门到实践,第十章练习题
10-1 Python学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In
Python you can”打头。将这个文件命名为 learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编
写一个程序,它读取这个文件,并将你所写的内容打印三次:
第一次打印时读取整个 文件;
path = "C:/Users/Administrator/Desktop/learning_python.txt"
with open(path) as paths:
lines=paths.read()
print(lines.rstrip())
第二次打印时遍历文件对象;
path = "C:/Users/Administrator/Desktop/learning_python.txt"
with open(path) as paths:
for lines in paths:
print(lines.rstrip())
第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。
path = "C:/Users/Administrator/Desktop/learning_python.txt"
with open(path) as paths:
lines=paths.readlines()
print(lines)
10-2 C语言学习笔记 :可使用方法replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如
何将句子中的'dog' 替换为'cat' :
>>> message = "I really like dogs."
>>> message.replace('dog', 'cat')
'I really like cats.'
读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都
打印到屏幕上。
path = "C:/Users/Administrator/Desktop/learning_python.txt"
with open(path) as paths:
line=paths.read()
print(line.rstrip().replace('Python','C'))
10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
path = "C:/Users/Administrator/Desktop/guest_book.txt"
with open(path,"w") as paths:
name=input("请输入名字:")
paths.write(name)
10-4 访客名单 :编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记
录添加到文件guest_book.txt中。确保这 个文件中的每条记录都独占一行。
path = "C:/Users/Administrator/Desktop/guest_book.txt"
print("请输入q退出")
while True:
name=input("请输入名字:")
if name=="q":
break
else:
print("hello "+name)
with open(path,"a") as paths:
paths.write(name+"")
10-5 关于编的调查 :编写一个while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原
因的文件中。
path = "C:/Users/Administrator/Desktop/pi_digits.txt"
print("请输入q退出")
while True: