第十章

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

print()
with open("The Zen of Python.txt") as file_object:
	for line in file_object:
		print(line)

print()
with open("The Zen of Python.txt") as file_object:
	lines = file_object.readlines()

for line in lines:
	print(line,end = " ")
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Beautiful is better than ugly.
 Explicit is better than implicit.
 Simple is better than complex. 
10-3 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
with open("guest.txt","w") as file_object:
	name = input("Please input your name:")
	file_object.write(name)
Please input your name:Alice

guest.txt:
Alice
10-4 访客名单:编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这 个文件中的每条记录都独占一行。
with open("guest_book.txt","a") as file_object:
	name = input("Please input your name:")
	while name != "q":
		file_object.write(name + "\n")
		name = input("Please input your name:")
Please input your name:Alice
Please input your name:Bob
Please input your name:Ben
Please input your name:q

10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引 发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
num1 = input("Please input the first integer:")
num2 = input("Please input the second integer:")
try:
	print(int(num1)+int(num2))
except TypeError:
	print("Please input the integers,NO other kinds of inputs.")
Please input the first integer:1
Please input the second integer:2
3
输入不是整数时,发现程序抛出的是ValueError,不是TypeError:
修改程序:

num1 = input("Please input the first integer:")
num2 = input("Please input the second integer:")
try:
	print(int(num1)+int(num2))
except ValueError:
	print("Please input the integers,NO other kinds of inputs.")
Please input the first integer:ze
Please input the second integer:5
Please input the integers,NO other kinds of inputs.





猜你喜欢

转载自blog.csdn.net/qq_36185481/article/details/79831796