10-1 Python学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为 learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个 文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。
代码
file_name = "learning_python.txt" with open(file_name) as file_object: contents = file_object.read() print(contents) with open(file_name) as file_object: for line in file_object: print(line.rstrip()) with open(file_name) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
输出结果
10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中
代码
file_name = "guest.txt" name = input("Please enter your name:") with open(file_name,'w') as file_object: file_object.write(name+"\n")
输出结果
10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发TypeError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
代码
a = input("please input a number:") b = input("please input another number:") try: print(int(a)+int(b)) except ValueError: print("Sorry, you must input numbers.")
输出结果