PythonCrashCourse 第十章习题

在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为 learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个 文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们

filename = 'learning_python.txt'
with open(filename) as file_object:
	contents = file_object.read()

print("the first style of reading the contents:")
print(contents)

print("
the second style of reading the contents:")
with open(filename) as file_object:
	for line in file_object:
		print(line.strip())

with open(filename) as file_object:
	lines = file_object.readlines()
print("
the third style of reading the contents:")
for line in lines:
	print(line.strip())

可使用方法replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的'dog' 替换为'cat' :

  • 读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。
filename = 'learning_python.txt'
with open(filename) as file_object:
	contents = file_object.read()

contents = contents.replace('python','java')
print(contents)

编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中

filename = 'guest.txt'
username = input('please enter your name:')

with open(filename,'a') as file_object:
	file_object.write(username+'
')

编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行

filename = 'guest_book.txt'

while True:
	name = input('Please enter your name,press Ctrl+c exit this terminal:')
	with open(filename,'a') as file_object:
		file_object.write(name+'
')
	print(f'welcome! {name.title()}')

编写一个while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中

filename = 'reasons.txt'

while True:
	reason = input("Why are you love to programming:")
	with open(filename,'a') as file_object:
		file_object.write(f'{reason} 
')

提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引 发TypeError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字

print("Give me two numbers and I'll add them.")
print("Enter 'q' to quit.")

while True:
	first_number = input("
First number:")
	if first_number == 'q':
		break
	second_number = input("Second number:")
	if second_number == 'q':
		break
	try:
		number_1 = int(first_number)
		number_2 = int(second_number)
		result = number_1 + number_2
	except ValueError as e:
		print("some input are not number.")
	else:
		print(f"The result is {result}")

将你为完成练习10-6而编写的代码放在一个while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字

print("Give me two numbers and I'll add them.")
print("Enter 'q' to quit.")

while True:
	first_number = input("
First number:")
	if first_number == 'q':
		break
	second_number = input("Second number:")
	if second_number == 'q':
		break
	try:
		number_1 = int(first_number)
		number_2 = int(second_number)
		result = number_1 + number_2
	except ValueError as e:
		print("some input are not number.")
	else:
		print(f"The result is {result}")

创建两个文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件, 并将其内容打印到屏幕上。

  • 将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,并打印一条友好的消息。将其中一个文件 移到另一个地方,并确认except 代码块中的代码将正确地执行

  • 修改你在练习10-8中编写的except 代码块,让程序在文件不存在时一言不发

def pets(filename):
	try:
		with open(filename) as f:
			contents =f.read()
	except FileNotFoundError as e:
		#print("cannot find the file.")
		pass
	else:
		print(f"The pets are:
{contents}")

filenames =['dogs.txt','cats.txt','puppys.txt']
for filename in filenames:
	pets(filename)
原文地址:https://www.cnblogs.com/CodingXu-jie/p/12841260.html