10-1 Python 学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至 此学到的 Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为 learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一 个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件; 第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在 with 代码 块外打印它们。
10-2C语言学习笔记:可使用方法replace()将字符串中的特定单词都替换为另一个单词。读取你刚创建的文件learning_python.txt 中的每一行,将其中的 Python都替换为另 一门语言的名称,如 C。将修改后的各行都打印到屏幕上。
filename = 'learning_python.txt' with open(filename) as file_object: whole_file = file_object.read() print(whole_file.rstrip()) file_object.seek(0) #返回文件头部 for line in file_object: print(line.rstrip()) file_object.seek(0) lines = file_object.readlines() for line in lines: print(line.rstrip()) #置换语句成分 print() for line in lines: print(line.rstrip().replace('Python', 'C++'))
10-3 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写 入到文件 guest.txt中。
10-4 访客名单:编写一个 while 循环,提示用户输入其名字。用户输入其名字后, 在屏幕上打印一句问候语,并将一条访问记录添加到文件 guest_book.txt 中。确保这个 文件中的每条记录都独占一行。
user_name = input("Input your user name to login:") while user_name.lower() != 'exit': with open('guest.txt', 'a') as user_file: user_file.write(user_name) print('Welcome ' + user_name + ' back.\n') with open('guest_book.txt', 'a') as record_file: record_file.write(user_name + ' login.') user_name = input("Input your user name to login:")
10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是 文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发 TypeError 异 常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的 任何一个值不是数字时都捕获 TypeError 异常,并打印一条友好的错误消息。对你编写 的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
10-7 加法计算器:将你为完成练习 10-6而编写的代码放在一个 while 循环中,让 用户犯错(输入的是文本而不是数字)后能够继续输入数字。
expression = input('Input your expression:') while expression.lower() != 'exit': operands = expression.split('+') sum = 0 for operand in operands: try: value = int(operand) except ValueError: print(operand + ' is not a integer.') break else: sum += value print(sum) expression = input('Input your expression:')